package com.example.contentprovider;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.net.Uri;

public class UsersProvider extends ContentProvider {

    private UserDao userDao;

    public UsersProvider() {
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // Implement this to handle requests to delete one or more rows.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public String getType(Uri uri) {
        // TODO: Implement this to handle requests for the MIME type of the data
        // at the given URI.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        UserEntity currentUserEntity = new UserEntity();
        if (values.containsKey(UserContract.MyDatas.KEY_COL_FIRSTNAME)) {
            currentUserEntity.firstname = values.getAsString(UserContract.MyDatas.KEY_COL_FIRSTNAME);
        }
        if (values.containsKey(UserContract.MyDatas.KEY_COL_NAME)) {
            currentUserEntity.name = values.getAsString(UserContract.MyDatas.KEY_COL_NAME);
        }
        long rowID = userDao.insert(currentUserEntity);
        if (rowID > 0) {
            Uri _uri = ContentUris.withAppendedId(UserContract.MyDatas.CONTENT_URI, rowID);
            getContext().getContentResolver().notifyChange(_uri, null);
            return _uri;
        }
        throw new SQLiteException("Failed to add a record into " + uri);
    }

    @Override
    public boolean onCreate() {
        Context context = getContext();
        userDao = AppDatabase.getDatabase(context).userDao();
        if (userDao != null) {
            return true;
        }

        return false;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        return userDao.getCursorAll();
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        // TODO: Implement this to handle requests to update one or more rows.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}
