package com.gs.apidemo;

import android.Manifest;
import android.app.AlertDialog;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.gs.account.api.BaseAccountApi;
import com.gs.account.entity.SipAccount;
import com.gs.contacts.context.ContactsContext;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;


/*
 */
public class ContactsActivity  extends BaseActivity {
    private static final String TAG = ContactsActivity.class.getSimpleName();
    private static final int REQUEST_CONTACTS = 1;
    private int accountId=-1;
    private long contactId;

    private ContentResolver contentResolver;
    private TextView resTv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts);

        contentResolver = getContentResolver();
        resTv = (TextView)findViewById(R.id.tv_res);
    }



    public void getContacts(View view) {
        if(checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_CONTACTS);
            return;
        }

        if(accountId == -1){
            Toast.makeText(this,"Enter accountId!",Toast.LENGTH_SHORT).show();
            return;
        }


        String[] projection = new String[]{
                ContactsContext.ContactsItem.ITEM_CONTACT_ID_IN_DATA,
                ContactsContext.ContactsItem.ITEM_ACCOUNT_ID,
                ContactsContext.ContactsItem.ITEM_PHONE_NUMBER,
                ContactsContext.ContactsItem.ITEM_DISPLAY_NAME
        };
        StringBuilder res = new StringBuilder("");
        Cursor cursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null,
                null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                long contactId = cursor.getLong(cursor.getColumnIndex(ContactsContext.ContactsItem.ITEM_CONTACT_ID_IN_DATA));
                long accountId = cursor.getInt(cursor.getColumnIndex(ContactsContext.ContactsItem.ITEM_ACCOUNT_ID));
                String number = cursor.getString(cursor.getColumnIndex(ContactsContext.ContactsItem.ITEM_PHONE_NUMBER));
                String name = cursor.getString(cursor.getColumnIndex(ContactsContext.ContactsItem.ITEM_DISPLAY_NAME));
                res.append("id:"+contactId+" ");
                res.append("number:"+number+ " ");
                res.append("accountId:"+accountId+ " ");
                res.append("displayName:"+name+" \n");
            }
            cursor.close();
        }
        if(TextUtils.isEmpty(res.toString())){
            resTv.setText("No results..");
        }else{
            resTv.setText(res.toString());
        }
    }


    public void getContacts() {
        String[] projection = new String[]{
                ContactsContext.ContactsItem.ITEM_CONTACT_ID_IN_DATA,
                ContactsContext.ContactsItem.ITEM_ACCOUNT_ID,
                ContactsContext.ContactsItem.ITEM_PHONE_NUMBER,
                ContactsContext.ContactsItem.ITEM_DISPLAY_NAME
        };

        Cursor cursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null,
                null, null);
        if (cursor != null) {

            while (cursor.moveToNext()) {
                long contactId = cursor.getLong(cursor.getColumnIndex(ContactsContext.ContactsItem.ITEM_CONTACT_ID_IN_DATA));
                long accountId = cursor.getInt(cursor.getColumnIndex(ContactsContext.ContactsItem.ITEM_ACCOUNT_ID));
                String number = cursor.getString(cursor.getColumnIndex(ContactsContext.ContactsItem.ITEM_PHONE_NUMBER));
                String name = cursor.getString(cursor.getColumnIndex(ContactsContext.ContactsItem.ITEM_DISPLAY_NAME));
            }
            cursor.close();
        }
    }


    public void deleteContact(View view){
        if(checkSelfPermission(Manifest.permission.WRITE_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.WRITE_CONTACTS}, REQUEST_CONTACTS);
            return;
        }
        String contactIdStr = ((EditText)findViewById(R.id.et_contactId)).getText().toString();
        if(TextUtils.isEmpty(contactIdStr)){
            Toast.makeText(this,"Enter accountId!",Toast.LENGTH_SHORT).show();
            return;
        }
        contactId = Long.parseLong(contactIdStr);

        deleteContactById(contactId);
        findViewById(R.id.btn_get_contacts_by_accountid).performClick();
    }



    public void deleteContactById(long contactId) {
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
        ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI)
                .withSelection(ContactsContract.RawContacts.CONTACT_ID+"="+contactId, null)
                .build());
        ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
                .withSelection(ContactsContract.Data.CONTACT_ID + "=" + contactId, null)
                .build());
        try {
            contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void addContact(View view) {
        if(checkSelfPermission(Manifest.permission.WRITE_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.WRITE_CONTACTS}, REQUEST_CONTACTS);
            return;
        }
        if(accountId == -1){
            Toast.makeText(this,"Enter accountId!",Toast.LENGTH_SHORT).show();
            return;
        }

        Random rand = new Random();
        int id = rand.nextInt(1000)-1;
        addContact("test"+ id,id+"",accountId);
        findViewById(R.id.btn_get_contacts_by_accountid).performClick();
    }


    public void addContact(String name,String number,long accountId) {
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
        int rawContactInsertIndex = ops.size();
        ops.add(ContentProviderOperation
                .newInsert(ContactsContract.RawContacts.CONTENT_URI)
                .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
                .withYieldAllowed(true).build());

        ops.add(ContentProviderOperation
                .newInsert(ContactsContract.Data.CONTENT_URI)
                .withValue(ContactsContext.ContactsItem.ITEM_ACCOUNT_ID, accountId)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,
                        rawContactInsertIndex)
                .withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name)
                .withYieldAllowed(true).build());

        ops.add(ContentProviderOperation
                .newInsert(android.provider.ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID,
                        rawContactInsertIndex)
                .withValue(ContactsContract.CommonDataKinds.Phone.MIMETYPE,
                        ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
                .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, number)
                .withYieldAllowed(true).build());
        try {
            contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void updateContact(long rawContactId,String name) {
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

        ops.add(ContentProviderOperation
                .newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(ContactsContract.Data.RAW_CONTACT_ID+"=?",
                        new String[]{rawContactId+""})
                .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name)
                .build());
        try {
            contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onClickSelectAccount(final View view) {
        final List<SipAccount> sipAccounts = BaseAccountApi.getAllSipAccounts();
        if (sipAccounts == null || sipAccounts.size() == 0) {
            Toast.makeText(this, "need add account first.", Toast.LENGTH_SHORT).show();
        }

        List<String> accountNames = new ArrayList<String>(sipAccounts.size());
        for (int i = 0; i < sipAccounts.size(); i++) {
            SipAccount account = sipAccounts.get(i);
            accountNames.add(account.getAccountId()+"["+account.getAccountName()+"]");
        }

        final String[] items = accountNames.toArray(new String[]{});
        AlertDialog.Builder listDialog =
                new AlertDialog.Builder(this);
        listDialog.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(ContactsActivity.this, "selected: " + items[which], Toast.LENGTH_SHORT).show();
                resTv.setText(items[which]);
                accountId = sipAccounts.get(which).getAccountId();

                Button button = (Button) view;
                button.setText("Sel AccountId: "+accountId);
            }
        });
        listDialog.show();
    }

}
