package com.gs.apidemo;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
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.sms.api.SmsManagerApi;
import com.gs.sms.context.SmsContext;
import com.gs.sms.listener.SmsListener;

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

public class SmsActivity extends BaseActivity {
    private static final String TAG = SmsActivity.class.getSimpleName();
    private EditText numberEt;
    private TextView resTv;
    private TextView accountTv;
    private boolean isGroup;
    private SipAccount mSelectedAccount = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms);

        mSelectedAccount = null;
        resTv = (TextView) findViewById(R.id.tv_res);
        resTv.setText("");
        accountTv = (TextView) findViewById(R.id.tv_account);
        numberEt = (EditText) findViewById(R.id.et_number);
        CheckBox box = (CheckBox) findViewById(R.id.box_is_group);
        box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isGroup = isChecked;
                if (isChecked) {
                    numberEt.setHint("Enter numbers connected with '_,' ");
                } else {
                    numberEt.setHint("Enter a number");
                }
            }
        });

        //Listen the msg send result to update the UI or do other.
        SmsManagerApi.addSmsListener(new SmsListener() {
            @Override
            public void onSend(long msgId, boolean sendOk) {
                appendNewResult("sms msgId： " + msgId + " sendOK:" + sendOk);
            }
        });

        //listen receive sms
        registerSmsReceiver();
    }

    private void appendNewResult(String nextStr) {
        String beforeLog = resTv.getText().toString();
        resTv.setText(beforeLog + "\n" + nextStr);
    }

    public void send(View view) {
        String numberStr = numberEt.getText().toString();
        String content = ((EditText) findViewById(R.id.et_content)).getText().toString();
        if (TextUtils.isEmpty(content)) {
            Toast.makeText(this, "Enter content", Toast.LENGTH_SHORT).show();
            return;
        }
        if (isGroup) {
            //Send to group
            if (TextUtils.isEmpty(numberStr)) {
                Toast.makeText(this, "Enter numbers", Toast.LENGTH_SHORT).show();
                return;
            }

            if (mSelectedAccount != null) {
                String res = sendToGroup(mSelectedAccount.getAccountId(), numberStr, content);
                resTv.setText(res);
            }
        } else {
            //Send to single one
            if (TextUtils.isEmpty(numberStr)) {
                Toast.makeText(this, "Enter a number", Toast.LENGTH_SHORT).show();
                return;
            }
            if (mSelectedAccount != null) {
                String res = sendToSingle(mSelectedAccount.getAccountId(), numberStr, content);
                resTv.setText(res);
            }
        }

    }

    private String sendToGroup(int accountId, String numberStr, String content) {
        StringBuilder res = new StringBuilder("");
        String[] numbers = numberStr.split("_,");
        if (numbers == null || numbers.length < 2) {
            Toast.makeText(this, "Make sure numbers input right.", Toast.LENGTH_SHORT).show();
            return "";
        }

        for (String number : numbers) {
            long msgId = SmsManagerApi.sendSmsAfterSaved(accountId, number, numberStr, content);
            if (msgId >= 0) {
                res.append("group sms to " + number + ",content:[" + content + "] will send,msgId：" + msgId + "\n");
            } else {
                res.append("group sms to " + number + ",content:[" + content + "] not save or send.Check number.\n");
            }
        }
        return res.toString();
    }


    private String sendToSingle(int accountId, String numberStr, String content) {
        long msgId = SmsManagerApi.sendSmsAfterSaved(accountId, numberStr, content);

        if (msgId >= 0) {
            return "sms to " + numberStr + ",content:[" + content + "] will send,msgId：" + msgId;
        } else {
            return "sms to " + numberStr + ",content:[" + content + "] not save or send.Check number.";
        }
    }

    private String resendFailedSms(long msgId) {
        boolean ret = SmsManagerApi.resendFailedSms(msgId);
        if (ret) {
            return "failed sms " + msgId + "will send..";
        } else {
            return "failed sms " + msgId + "not send.";
        }
    }


    @Override
    protected void onDestroy() {
        unRegisterSmsReceiver();
        super.onDestroy();
    }

    /*For Receive sms*/
    private SmsReceiver smsReceiver;

    private void registerSmsReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(SmsContext.SMS_RECEIVED_ACTION);
        smsReceiver = new SmsReceiver();
        registerReceiver(smsReceiver, filter);
    }

    private void unRegisterSmsReceiver() {
        if (smsReceiver != null) {
            unregisterReceiver(smsReceiver);
        }
    }

    class SmsReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("SmsActivity", "onReceive:" + intent.getAction());
            if (SmsContext.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
                long id = intent.getLongExtra(SmsContext.ReceiveSms.ID, -1);
                String number = intent.getStringExtra(SmsContext.ReceiveSms.NUMBER);
                int accountId = intent.getIntExtra(SmsContext.ReceiveSms.ACCOUNT_ID, -1);
                String content = intent.getStringExtra(SmsContext.ReceiveSms.CONTENT);

                appendNewResult("Receive msgId:" + id + ", from:" + number + ", to accountId:" + accountId + ", content:" + content);
            }
        }
    }

    public void onClickSelectAccount(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.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(SmsActivity.this, "selected: " + items[which], Toast.LENGTH_SHORT).show();
                accountTv.setText(items[which]);
                mSelectedAccount = sipAccounts.get(which);
            }
        });
        listDialog.show();
    }
}
