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.CallLog;
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.calllog.context.CallLogContext;

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


/*
 */
public class CallLogsActivity extends BaseActivity {
    private static final String TAG = CallLogsActivity.class.getSimpleName();
    private static final int REQUEST_CALL_LOG = 1;
    private int accountId=-1;
    private long calllogId;

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

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

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

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

        Cursor cursor = contentResolver.query(CallLogContext.CALL_LOG_URI,
                null, null,null , null);
        StringBuilder res = new StringBuilder("");

        if(cursor!= null){
            if(cursor.moveToFirst()){
                do{
                    long calllogId = cursor.getLong(cursor.getColumnIndex(CallLogContext.CallLogItem.ITEM_ID));
                    res.append("id:"+calllogId+" ");
                    res.append("cache name:"+cursor.getString(cursor.getColumnIndex(CallLogContext.CallLogItem.ITEM_CACHE_NAME))+ " ");
                    //ITEM_CALL_MODE support on GXV3370
//                    res.append("mode:"+cursor.getLong(cursor.getColumnIndex(CallLogContext.CallLogItem.ITEM_CALL_MODE))+ " ");
                    res.append("type:"+cursor.getLong(cursor.getColumnIndex(CallLogContext.CallLogItem.ITEM_CALL_TYPE))+" ");
                    res.append("media type:"+(cursor.getLong(cursor.getColumnIndex(CallLogContext.CallLogItem.ITEM_MEDIA_TYPE))==1?"video":"audio")+" \n");
                }while (cursor.moveToNext());
            }

            cursor.close();
        }

        if(TextUtils.isEmpty(res.toString())){
            resTv.setText("No results..");
        }else{
            resTv.setText(res.toString());
        }
    }

    public void getCallLogs() {
        Cursor cursor = contentResolver.query(CallLogContext.CALL_LOG_URI,
                null, null,null , null);
        StringBuilder res = new StringBuilder("");
        if(cursor!= null){
            if(cursor.moveToFirst()){
                do{
                    long calllogId = cursor.getLong(cursor.getColumnIndex(CallLogContext.CallLogItem.ITEM_ID));
                    String cacheName = cursor.getString(cursor.getColumnIndex(CallLogContext.CallLogItem.ITEM_CACHE_NAME));
                    int mediaType = cursor.getInt(cursor.getColumnIndex(CallLogContext.CallLogItem.ITEM_MEDIA_TYPE));
                }while (cursor.moveToNext());
            }

            cursor.close();
        }
    }

    public void deleteCalllog(View view){
        if(checkSelfPermission(Manifest.permission.WRITE_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.WRITE_CALL_LOG}, REQUEST_CALL_LOG);
            return;
        }
        String calllogIdStr = ((EditText)findViewById(R.id.et_callogId)).getText().toString();
        if(TextUtils.isEmpty(calllogIdStr)){
            Toast.makeText(this,"Enter accountId!",Toast.LENGTH_SHORT).show();
            return;
        }
        calllogId = Long.parseLong(calllogIdStr);

        deleteCalllogById(calllogId);
        findViewById(R.id.btn_get_logs_by_accountid).performClick();

    }

    public void deleteCalllogById(long callId) {
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
        ops.add(ContentProviderOperation.newDelete(CallLogContext.CALL_LOG_URI)
                .withSelection(CallLogContext.CallLogItem.ITEM_ID+"="+callId, null)
                .build());

        try {
            contentResolver.applyBatch(CallLog.AUTHORITY, ops);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void updateCalllogById(long callId) {
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
        ops.add(ContentProviderOperation.newUpdate(CallLogContext.CALL_LOG_URI)
                .withSelection(CallLogContext.CallLogItem.ITEM_ID+"="+callId, null)
                .withValue(CallLogContext.CallLogItem.ITEM_DURATION,1000)
                .build());

        try {
            contentResolver.applyBatch(CallLog.AUTHORITY, ops);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void addCalllog(View view) {
        if(checkSelfPermission(Manifest.permission.WRITE_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.WRITE_CALL_LOG}, REQUEST_CALL_LOG);
            return;
        }
        if(accountId == -1){
            Toast.makeText(this,"Select accountId!",Toast.LENGTH_SHORT).show();
            return;
        }

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


    public void addCalllog(String name,String number,long accountId) {
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

        ops.add(ContentProviderOperation.newInsert(CallLogContext.CALL_LOG_URI)
                .withValue(CallLogContext.CallLogItem.ITEM_ACCOUNT, accountId)
                .withValue(CallLogContext.CallLogItem.ITEM_CACHE_NAME, name)
                //ITEM_CALL_MODE support on GXV3370
//                .withValue(CallLogContext.CallLogItem.ITEM_CALL_MODE, PhoneContext.CallMode.SIP_CALL)
                .withValue(CallLogContext.CallLogItem.ITEM_START_TIME, System.currentTimeMillis())
                .withValue(CallLogContext.CallLogItem.ITEM_IS_IN_CONFERENCE,false)
                .withValue(CallLogContext.CallLogItem.ITEM_NUMBER_ORIGINAL,number)
                .withValue(CallLogContext.CallLogItem.ITEM_NUMBER,number)
                .withValue(CallLogContext.CallLogItem.ITEM_CALL_TYPE, CallLogContext.CallLogType.TYPE_MISSED)
                .withValue(CallLogContext.CallLogItem.ITEM_DURATION, 0)
                .withValue(CallLogContext.CallLogItem.ITEM_MEDIA_TYPE, CallLogContext.MediaType.AUDIO)
                .build());
        try {
            contentResolver.applyBatch(CallLog.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(CallLogsActivity.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();
    }

}
