package br.com.trimsy.contacts;

import android.Manifest;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.provider.ContactsContract;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedHashMap;

public class TrimsyContacts extends CordovaPlugin {
    private static final int REQ_READ = 7913;
    private CallbackContext pending;

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (!"list".equals(action)) return false;
        if (cordova.hasPermission(Manifest.permission.READ_CONTACTS)) {
            list(callbackContext);
        } else {
            pending = callbackContext;
            cordova.requestPermission(this, REQ_READ, Manifest.permission.READ_CONTACTS);
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException {
        if (requestCode != REQ_READ || pending == null) return;
        CallbackContext cb = pending;
        pending = null;
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            list(cb);
        } else {
            cb.error("denied");
        }
    }

    private void list(final CallbackContext cb) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                try {
                    cb.success(readContacts());
                } catch (Exception e) {
                    cb.error(e.getMessage() != null ? e.getMessage() : "read_failed");
                }
            }
        });
    }

    private JSONArray readContacts() throws JSONException {
        LinkedHashMap<String, JSONObject> map = new LinkedHashMap<String, JSONObject>();
        Cursor phones = cordova.getActivity().getContentResolver().query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            new String[] {
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER
            },
            null,
            null,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC"
        );
        if (phones != null) {
            while (phones.moveToNext()) {
                String id = phones.getString(0);
                if (id == null || id.length() == 0) continue;
                String name = phones.getString(1);
                String phone = phones.getString(2);
                JSONObject row = map.get(id);
                if (row == null) {
                    row = new JSONObject();
                    row.put("id", id);
                    row.put("name", name != null ? name : "");
                    row.put("phone", phone != null ? phone : "");
                    map.put(id, row);
                } else if ((row.optString("phone").length() == 0) && phone != null) {
                    row.put("phone", phone);
                }
            }
            phones.close();
        }
        JSONArray out = new JSONArray();
        for (JSONObject row : map.values()) out.put(row);
        return out;
    }
}
