package com.kfzs.duanduan.data.graph.provider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import com.kfzs.duanduan.data.graph.provider.channel.ChannelDao;
import com.kfzs.duanduan.data.graph.provider.channel.DaoMaster;
import com.kfzs.duanduan.datashare.BuildConfig;

import java.util.Arrays;

/**
 * @author kemllor
 * @date 2017/6/13   2:03
 **/

public class KFZSProvider extends ContentProvider {
    public static final String TAG = "KFZSProvider";
    public static final String QUERY_NOTIFY = "QUERY_NOTIFY";
    public static final String QUERY_GROUP_BY = "QUERY_GROUP_BY";
    public static final String QUERY_HAVING = "QUERY_HAVING";
    public static final String QUERY_LIMIT = "QUERY_LIMIT";


    private static final String TYPE_CURSOR_ITEM = "vnd.android.cursor.item/";
    private static final String TYPE_CURSOR_DIR = "vnd.android.cursor.dir/";
    public static final String AUTHORITY = "com.kfzs.duanduan.data.graph.provider";
    public static final String CONTENT_URI_BASE = "content://" + AUTHORITY;


    private static final UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);

    private static final int URI_TYPE_USER = 0;
    private static final int URI_TYPE_USER_ID = 1;

    private static final int URI_TYPE_DOWNLOADTASK = 2;
    private static final int URI_TYPE_DOWNLOADTASK_ID = 3;
    private static final int URI_TYPE_CHANNEL = 4;


    static {
//        URI_MATCHER.addURI(AUTHORITY, UserDao.TABLENAME, URI_TYPE_USER);
//        URI_MATCHER.addURI(AUTHORITY, UserDao.TABLENAME + "/#", URI_TYPE_USER_ID);
//        URI_MATCHER.addURI(AUTHORITY, DownLoadInfoDao.TABLENAME, URI_TYPE_DOWNLOADTASK);
//        URI_MATCHER.addURI(AUTHORITY, DownLoadInfoDao.TABLENAME + "/#", URI_TYPE_DOWNLOADTASK_ID);
        URI_MATCHER.addURI(AUTHORITY, ChannelDao.TABLENAME, URI_TYPE_CHANNEL);
    }

    private SQLiteDatabase mDatabase;


    @Override
    public boolean onCreate() {
        DaoMaster.OpenHelper openHelper = new DaoMaster.DevOpenHelper(getContext(), "dd.db");
        mDatabase = openHelper.getWritableDatabase();
        return false;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "query uri=" + uri + " selection=" + selection + " selectionArgs=" + Arrays.toString(selectionArgs) + " sortOrder=" + sortOrder
                    + " groupBy=" + uri.getQueryParameter(QUERY_GROUP_BY) + " having=" + uri.getQueryParameter(QUERY_HAVING) + " limit=" + uri.getQueryParameter(QUERY_LIMIT));
        }
        String groupBy = uri.getQueryParameter(QUERY_GROUP_BY);
        String having = uri.getQueryParameter(QUERY_HAVING);
        String limit = uri.getQueryParameter(QUERY_LIMIT);
        QueryParams queryParams = getQueryParams(uri, selection, projection);
        Cursor res = mDatabase.query(queryParams.table, projection, queryParams.selection, selectionArgs, groupBy,
                having, sortOrder == null ? queryParams.orderBy : sortOrder, limit);
        if (getContext() != null)
            res.setNotificationUri(getContext().getContentResolver(), uri);
        return res;
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        int match = URI_MATCHER.match(uri);
        switch (match) {
           /* case URI_TYPE_USER:
                return TYPE_CURSOR_DIR + UserDao.TABLENAME;
            case URI_TYPE_USER_ID:
                return TYPE_CURSOR_ITEM + UserDao.TABLENAME;
            case URI_TYPE_DOWNLOADTASK:
                return TYPE_CURSOR_DIR + DownLoadInfoDao.TABLENAME;
            case URI_TYPE_DOWNLOADTASK_ID:
                return TYPE_CURSOR_ITEM + DownLoadInfoDao.TABLENAME;*/
            case URI_TYPE_CHANNEL:
                return TYPE_CURSOR_ITEM + ChannelDao.TABLENAME;
        }
        return null;
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "insert uri=" + uri + " values=" + values);
        }
        String table = uri.getLastPathSegment();
        long rowId = mDatabase.insert(table, null, values);
        if (rowId == -1)
            return null;
        String notify;
        if (((notify = uri.getQueryParameter(QUERY_NOTIFY)) == null || "true".equals(notify))) {
            if (getContext() != null)
                getContext().getContentResolver().notifyChange(uri, null);
        }
        return uri.buildUpon().appendEncodedPath(String.valueOf(rowId)).build();
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "delete uri=" + uri + " selection=" + selection + " selectionArgs=" + Arrays.toString(selectionArgs));
        }
        QueryParams queryParams = getQueryParams(uri, selection, null);
        int res = mDatabase.delete(queryParams.table, queryParams.selection, selectionArgs);
        String notify;
        if (res != 0 && ((notify = uri.getQueryParameter(QUERY_NOTIFY)) == null || "true".equals(notify))) {
            if (getContext() != null)
                getContext().getContentResolver().notifyChange(uri, null);
        }
        return res;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "update uri=" + uri + " values=" + values + " selection=" + selection + " selectionArgs=" + Arrays.toString(selectionArgs));
        }

        QueryParams queryParams = getQueryParams(uri, selection, null);
        int res = mDatabase.update(queryParams.table, values, queryParams.selection, selectionArgs);
        String notify;
        if (res != 0 && ((notify = uri.getQueryParameter(QUERY_NOTIFY)) == null || "true".equals(notify))) {
            if (getContext() != null)
                getContext().getContentResolver().notifyChange(uri, null);
        }
        return res;
    }

    protected QueryParams getQueryParams(Uri uri, String selection, String[] projection) {
        QueryParams res = new QueryParams();
        int matchedId = URI_MATCHER.match(uri);
        switch (matchedId) {
          /*  case URI_TYPE_DOWNLOADTASK:
            case URI_TYPE_DOWNLOADTASK_ID:
                res.table = DownLoadInfoDao.TABLENAME;
                res.idColumn = DownLoadInfoDao.Properties.MGameID.columnName;
                break;
            case URI_TYPE_USER:
            case URI_TYPE_USER_ID:
                res.table = UserDao.TABLENAME;
                res.idColumn = UserDao.Properties.MUserId.columnName;
                break;*/
            case URI_TYPE_CHANNEL:
                res.table = ChannelDao.TABLENAME;
                res.idColumn = ChannelDao.Properties.MChannelName.columnName;
                break;

            default:
                throw new IllegalArgumentException("The uri '" + uri + "' is not supported by this ContentProvider");
        }

       /* switch (matchedId) {
            case URI_TYPE_DOWNLOADTASK_ID:
            case URI_TYPE_USER_ID:
                id = uri.getLastPathSegment();
        }
        if (id != null) {
            if (selection != null) {
                res.selection = res.table + "." + res.idColumn + "=" + id + " and (" + selection + ")";
            } else {
                res.selection = res.table + "." + res.idColumn + "=" + id;
            }
        } else {
            res.selection = selection;
        }*/

        res.selection = selection;
        return res;
    }

    public static class QueryParams {
        public String table;
        public String idColumn;
        public String selection;
        public String orderBy;
    }


}
