package com.example.nuria.fesp_cyl.utils;

import android.content.ContentProvider;
import android.content.ContentUris;
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.text.TextUtils;
import android.util.Log;

import com.example.nuria.fesp_cyl.DataBase.DbHelper;
import com.example.nuria.fesp_cyl.DataBase.StatusContract;


public class UrlsProvider extends ContentProvider {

    private static final String TAG = UrlsProvider.class.getSimpleName();
    private DbHelper dbHelper;

    private static final UriMatcher urlsURIMatcher;
    static {
        urlsURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        urlsURIMatcher.addURI(StatusContract.AUTHORITY_URL, StatusContract.TABLE_URL ,
                StatusContract.STATUS_DIR_URL);
        urlsURIMatcher.addURI(StatusContract.AUTHORITY_URL, StatusContract.TABLE_URL + "/#",
                StatusContract.STATUS_ITEM_URL);
    }

    @Override
    public boolean onCreate() {
        dbHelper = new DbHelper(getContext());
        Log.d(TAG, "onCreated");
        return true;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] strings, @Nullable String s,
                        @Nullable String[] strings1, @Nullable String s1) {
        String where;
        switch (urlsURIMatcher.match(uri)) {
            case StatusContract.STATUS_DIR_URL:
                where = s;
                break;
            case StatusContract.STATUS_ITEM_URL:
                long id = ContentUris.parseId(uri);
                where = StatusContract.ColumnUrls.IDURL
                        + "="
                        + id
                        + (TextUtils.isEmpty(s) ? "" : " and ( " + s + " )");
                break;
            default:
                throw new IllegalArgumentException("uri incorrecta: " + uri);
        }
        String orderBy = (TextUtils.isEmpty(s1)) ? StatusContract.DEFAULT_SORT_URL : s1;
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(StatusContract.TABLE_URL, strings, where, strings1, null, null,
                orderBy);
        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        Log.d(TAG, "registros recuperados: " + cursor.getCount());
        return cursor;
    }

    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        switch (urlsURIMatcher.match(uri)) {
            case StatusContract.STATUS_DIR_URL:
                Log.d(TAG, "gotType: vnd.android.cursor.dir/vnd.com.example.nuria.fesp_cyl.provider.urls");
                return "vnd.android.cursor.dir/vnd.com.example.nuria.fesp_cyl.provider.urls";
            case StatusContract.STATUS_ITEM_URL:
                Log.d(TAG, "gotType: vnd.android.cursor.item/vnd.com.example.nuria.fesp_cyl.provider.urls");
                return "vnd.android.cursor.item/vnd.com.example.nuria.fesp_cyl.provider.urls";
            default:
                throw new IllegalArgumentException("uri incorrecta: " + uri);
        }
    }

    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) {
        Uri ret = null;

        // Nos aseguramos de que la URI es correcta
        if (urlsURIMatcher.match(uri) != StatusContract.STATUS_DIR_URL) {
            throw new IllegalArgumentException("uri incorrecta: " + uri);
        }
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        long rowId = db.insertWithOnConflict(StatusContract.TABLE_URL, null,
                contentValues, SQLiteDatabase.CONFLICT_IGNORE);
        return ret;
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) {
        String where;
        switch (urlsURIMatcher.match(uri)) {
            case StatusContract.STATUS_DIR_URL:
                where = s;
                break;
            case StatusContract.STATUS_ITEM_URL:
                long id = ContentUris.parseId(uri);
                where = StatusContract.ColumnUrls.IDURL
                        + "="
                        + id
                        + (TextUtils.isEmpty(s) ? "" : " and ( " + s + " )");
                break;
            default:
                throw new IllegalArgumentException("uri incorrecta: " + uri);
        }
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int ret = db.delete(StatusContract.TABLE_URL, where, strings);
        if (ret > 0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        Log.d(TAG, "registros borrados: " + ret);
        return ret;
    }


    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s,
                      @Nullable String[] strings) {
        String where;
        //Actualizar dos registros con update(), utilizando argumentos
        switch (urlsURIMatcher.match(uri)) {
            case StatusContract.STATUS_DIR_URL:
                where = s;
                break;
            case StatusContract.STATUS_ITEM_URL:
                long id = ContentUris.parseId(uri);
                where = StatusContract.ColumnUrls.IDURL
                        + "="
                        + id
                        + (TextUtils.isEmpty(s) ? "" : " and ( " + s + " )");
                break;
            default:
                throw new IllegalArgumentException("uri incorrecta: " + uri);
        }
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int ret = db.update(StatusContract.TABLE_URL, contentValues, where, strings);
        if (ret > 0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        Log.d(TAG, "registros actualizados: " + ret);
        return ret;
    }
}
