package com.honu.giftwise;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by bdiegel on 2/24/15.
 */
public class ContactsUtils {

    public static final String DISPLAY_NAME = "display_name";

    private static final String LOG_TAG = ContactsUtils.class.getSimpleName();

    public static void createRawContact(Context context, String accountName, String displayName) {

        String accountType = context.getString(R.string.account_type);

        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

        int rawContactInsertIndex = ops.size();
        ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
              .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, accountType)
              .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, accountName)
              .build());

        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
              .withValueBackReference(ContactsContract.RawContacts.Data.RAW_CONTACT_ID, rawContactInsertIndex)
              .withValue(ContactsContract.RawContacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
              .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName)
              .build());

        try {
            context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (OperationApplicationException e) {
            e.printStackTrace();
        }


    }


    public static void readRawAccountTypes(Context context) {
        String mAcccountName = "*";
        String mAccountType = "*";

        Cursor cursor = context.getContentResolver().query(
              ContactsContract.RawContacts.CONTENT_URI,
              new String[]{ContactsContract.RawContacts._ID, ContactsContract.RawContacts.ACCOUNT_NAME, ContactsContract.RawContacts.ACCOUNT_TYPE, ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY},
              null,
              null,
              null
        );

        while (cursor.moveToNext()) {
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts._ID));
            String acctName = cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME));
            String acctType = cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE));
            String dispName = cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY));
            Log.i(LOG_TAG, "Found account: id=" + id + " name=" + acctName + " type=" + acctType + " display=" + dispName);
        }
        cursor.close();
    }

    public static String getUsername(Context context) {
        AccountManager manager = AccountManager.get(context);
        Account[] accounts = manager.getAccountsByType("com.google");
        List<String> possibleEmails = new LinkedList<String>();

        for (Account account : accounts) {
            // TODO: Check possibleEmail against an email regex or treat
            // account.name as an email address only for certain account.type
            // values.

            String possibleEmail = account.name;
            String type = account.type;

            if (type.equals("com.google")) {
                Log.e("", "Emails: " + possibleEmail);
                break;
            }

            possibleEmails.add(possibleEmail);
        }

        if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
            String email = possibleEmails.get(0);
            String[] parts = email.split("@");
            if (parts.length > 0 && parts[0] != null)
                return parts[0];
            else
                return null;
        } else
            return null;
    }

    private Loader<Cursor> loadContacts(Context context, String[] projection) {
        // defined query arguments:
        final Uri uri = ContactsContract.Contacts.CONTENT_URI;
        final String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1'";
        final String[] selectionArgs = null;
        final String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";

        return new CursorLoader(
              context,
              uri,
              projection,
              selection,
              selectionArgs,
              sortOrder
        );
    }
}

@@ -770,24 +770,188 @@
 pleName();%0A%0A
+%0A    /**%0A     * Create a new RawContact for our app-specific account type.%0A     *%0A     * @param context%0A     * @param accountName%0A     * @param displayName%0A     */%0A
     public s
@@ -2271,141 +2271,221 @@
  %7D%0A%0A
-%0A    public static void readRawAccountTypes(Context context) %7B%0A        String mAcc
+    /**%0A     * List all the RawContacts from the content provider. Convenience function to quickly check contents.%0A     *%0A     * @param 
 co
-u
 nt
-Name = %22*%22;%0A        String mAccountType = %22*%22;
+ext%0A     */%0A    public static void readRawAccountTypes(Context context) %7B
 %0A%0A  
@@ -4624,24 +4624,168 @@
 ull;%0A    %7D%0A%0A
+    /**%0A     * Load all visible Contacts from the content provider%0A     *%0A     * @param context%0A     * @param projection%0A     * @return%0A     */%0A
     private 
@@ -4848,24 +4848,25 @@
 ojection) %7B%0A
+%0A
         // d

Document functions that query and modify contacts