/*
 * Copyright (c) 2015. Ncomz. All Rights Reserved
 */

package com.ntels.onecable.admin.view.dialog;

import com.ntels.onecable.admin.R;
import com.ntels.onecable.admin.common.AppConfig;
import com.ntels.onecable.admin.common.Constants;
import com.ntels.onecable.admin.common.c_interface.OnDataSendToReslut;
import com.ntels.onecable.admin.common.db.DatabaseOpenHelper;
import com.ntels.onecable.admin.common.db.SqlManager;
import com.ntels.onecable.admin.common.db.entity.TblLoginInfo;
import com.ntels.onecable.admin.common.http.HttpSend;
import com.ntels.onecable.admin.common.http.Response;
import com.ntels.onecable.admin.common.util.Dlog;
import com.ntels.onecable.admin.common.util.LogUtil;
import com.ntels.onecable.admin.common.util.Util;
import com.tsengvn.typekit.TypekitContextWrapper;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * <pre>
 * 1. ClassName :   PushDialog
 * 2. FileName  :   PushDialog.java
 * 3. Package   :   com.ntels.onecable.admin.view.dialog
 * 4. Date      :   2016-12-01
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class PushDialog extends Activity implements OnDismissListener {

    private static final String TAG = PushDialog.class.getSimpleName();

    private static final int MSG_COM_G_DEVICES_WARNING_NODES = 1;

    public static Activity mActivity;
    public Util mUtil = new Util();
    public AppConfig mAppConfig;
    public String body = "";
    public String pushTypeCode = "";
    public String buttonName = "";
    public String homegrpId = "";
    public String appProc = "";
    Handler comHandler = new Handler(new IncomingHandlerCallBack());
    private Boolean dialogCheck = false;
    private Dialog dialog;
    /*통신 관련*/
    private int type = 0;

    @Override
    protected void attachBaseContext(Context newBase) {

        super.attachBaseContext(TypekitContextWrapper.wrap(newBase));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        mActivity = PushDialog.this;
        overridePendingTransition(0, 0);
        setContentView(R.layout.push_alram_dialog);
        mAppConfig = (AppConfig) mActivity.getApplicationContext();

        if (savedInstanceState != null) {
            body = savedInstanceState.getString(Constants.EXTRA_BODY);
            pushTypeCode = savedInstanceState.getString(Constants.EXTRA_PUSH_TYPE_CODE);
            buttonName = savedInstanceState.getString(Constants.EXTRA_BUTTON_NAME);
            homegrpId = savedInstanceState.getString(Constants.EXTRA_HOMEGRP_ID);
            appProc = savedInstanceState.getString(Constants.EXTRA_APP_PROC);
        } else {
            Intent intent = mActivity.getIntent();
            body = intent.getStringExtra(Constants.EXTRA_BODY);
            pushTypeCode = intent.getStringExtra(Constants.EXTRA_PUSH_TYPE_CODE);
            buttonName = intent.getStringExtra(Constants.EXTRA_BUTTON_NAME);
            homegrpId = intent.getStringExtra(Constants.EXTRA_HOMEGRP_ID);
            appProc = intent.getStringExtra(Constants.EXTRA_APP_PROC);
        }
        dialogCheck = false;
        callMsgAlert(body);
    }

    @Override
    protected void onDestroy() {

        try {
            Dlog.v("onDestroy");

            if (dialog != null) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                dialog = null;
            }
            dialogCheck = false;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        super.onDestroy();
    }

    @Override
    public void finish() {

        super.finish();
        overridePendingTransition(0, 0);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {

        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            body = savedInstanceState.getString(Constants.EXTRA_BODY);
            pushTypeCode = savedInstanceState.getString(Constants.EXTRA_PUSH_TYPE_CODE);
            buttonName = savedInstanceState.getString(Constants.EXTRA_BUTTON_NAME);
            homegrpId = savedInstanceState.getString(Constants.EXTRA_HOMEGRP_ID);
            appProc = savedInstanceState.getString(Constants.EXTRA_APP_PROC);
            callMsgAlert(body);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
        outState.putString(Constants.EXTRA_BODY, body);
        outState.putString(Constants.EXTRA_PUSH_TYPE_CODE, pushTypeCode);
        outState.putString(Constants.EXTRA_BUTTON_NAME, buttonName);
        outState.putString(Constants.EXTRA_HOMEGRP_ID, homegrpId);
        outState.putString(Constants.EXTRA_APP_PROC, appProc);
    }

    @Override
    protected void onNewIntent(Intent intent) {

        super.onNewIntent(intent);
        Dlog.v("onNewIntent");
        overridePendingTransition(0, 0);
        if (intent != null) {
            body = intent.getStringExtra(Constants.EXTRA_BODY);
            pushTypeCode = intent.getStringExtra(Constants.EXTRA_PUSH_TYPE_CODE);
            buttonName = intent.getStringExtra(Constants.EXTRA_BUTTON_NAME);
            homegrpId = intent.getStringExtra(Constants.EXTRA_HOMEGRP_ID);
            appProc = intent.getStringExtra(Constants.EXTRA_APP_PROC);
            if (dialog != null) {
                if (dialog.isShowing()) {
                    dialogCheck = true;
                } else {
                    dialogCheck = false;
                }
            } else {
                dialogCheck = false;
            }
            callMsgAlert(body);
        }
    }

    /**
     * {@link #msgAlert(String)} 호출.
     *
     * @param msg Message
     */
    public void callMsgAlert(String msg) {

        if (pushTypeCode.equals("MEM_ALL_OUT")) {

            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DEVICES_WARNING_NODES), 10);
        } else {
            if (dialogCheck) {
                ((TextView) dialog.findViewById(R.id.tvBody)).setText(body);
            } else {
                msgAlert(body);
            }
        }
    }

    /**
     * Message box dialog.
     *
     * @param msg Message
     */
    private void msgAlert(String msg) {

        String positiveButtonText = "";
        String negativeButtonText = "";
        int msgNo = Constants.MSG000;
        if (pushTypeCode.equals("HOME_MEM_INV")) {
            //    홈 초대 받음
            if (appProc.equals("STOP")) {
                positiveButtonText = mUtil.getString(mActivity, R.string.MSG_BTN_APP_START);
                negativeButtonText = mUtil.getString(mActivity, R.string.MSG_BTN_CLOSE);
            } else {
                positiveButtonText = mUtil.getString(mActivity, R.string.MSG_BTN_CONFIRM);
                negativeButtonText = mUtil.getString(mActivity, R.string.MSG_BTN_LATER);
            }
        } else if (pushTypeCode.equals("HOME_MEM_REF")) {
            //    초대했는데 거절 당할 시
            positiveButtonText = mUtil.getString(mActivity, R.string.MSG_BTN_CONFIRM);
            negativeButtonText = "";
        } else if (pushTypeCode.equals("HOME_MEM_BAN")) {
            LogUtil.i(TAG, "msgAlert : HOME_MEM_BAN");
            //    홈 강퇴 받음
            positiveButtonText = mUtil.getString(mActivity, R.string.MSG_BTN_CONFIRM);
            negativeButtonText = "";
        } else if (pushTypeCode.equals("HOME_MEM_SEL")) {
            //    홈 자진탈퇴 받음
            positiveButtonText = mUtil.getString(mActivity, R.string.MSG_BTN_CONFIRM);
            negativeButtonText = "";
        } else if (pushTypeCode.equals("HOME_DEL")) {
            //    홈 삭제
            positiveButtonText = mUtil.getString(mActivity, R.string.MSG_BTN_CONFIRM);
            negativeButtonText = "";
        } else if (pushTypeCode.equals("DVC_CER_REV")) {
            //    단말 인증 해지 됨
            positiveButtonText = mUtil.getString(mActivity, R.string.MSG_BTN_CONFIRM);
            negativeButtonText = "";
        } else if (pushTypeCode.equals("MODE_CHG")) {
            //    MODE_CHG
            positiveButtonText = mUtil.getString(mActivity, R.string.MSG_BTN_CONFIRM);
            negativeButtonText = "";
        } else if (pushTypeCode.equals("MODE_CHG_ERR")) {
            //    MODE_CHG_ERR
            positiveButtonText = mUtil.getString(mActivity, R.string.MSG_BTN_CONFIRM);
            negativeButtonText = "";
        } else if (pushTypeCode.equals("RULE_EXC")) {
            //    규칙의 액션 결과
            positiveButtonText = mUtil.getString(mActivity, R.string.MSG_BTN_CONFIRM);
            negativeButtonText = "";
        } else if (pushTypeCode.equals("RULE_ERR")) {
            //    규칙의 액션 결과
            positiveButtonText = mUtil.getString(mActivity, R.string.MSG_BTN_CONFIRM);
            negativeButtonText = "";
        } else if (pushTypeCode.equals("HOMEHUB_DEL")) {
            //    홈 허브가 삭제됨
            positiveButtonText = mUtil.getString(mActivity, R.string.MSG_BTN_CONFIRM);
            negativeButtonText = "";
        } else if (pushTypeCode.equals("DVC_OWN_CHG")) {
            //    장치 소유주 변경 알림
            positiveButtonText = mUtil.getString(mActivity, R.string.MSG_BTN_CONFIRM);
            negativeButtonText = "";
        } else if (pushTypeCode.equals("MEM_ALL_OUT")) {
            //    멤버 All out 시
            if (appProc.equals("STOP")) {
                positiveButtonText = mUtil.getString(mActivity, R.string.MSG_BTN_APP_START);
                negativeButtonText = mUtil.getString(mActivity, R.string.MSG_BTN_CLOSE);
            } else {
                positiveButtonText = mUtil.getString(mActivity, R.string.MSG_BTN_CONFIRM);
                negativeButtonText = "";
            }
        } else if (pushTypeCode.equals("MEM_ANY_IN")) {
            //    멤버 Any in 시
            if (appProc.equals("STOP")) {
                positiveButtonText = mUtil.getString(mActivity, R.string.MSG_BTN_APP_START);
                negativeButtonText = mUtil.getString(mActivity, R.string.MSG_BTN_CLOSE);
            } else {
                positiveButtonText = mUtil.getString(mActivity, R.string.MSG_BTN_CONFIRM);
                negativeButtonText = "";
            }
        } else {
            positiveButtonText = mUtil.getString(mActivity, R.string.MSG_BTN_CONFIRM);
            negativeButtonText = "";
        }

        DialogCustom.Builder dialogBuilder;
        dialogBuilder = new DialogCustom.Builder(mActivity);
        if (msgNo != 0) {
            dialogBuilder.setErrNo("MSG" + msgNo);
        }
        if (!msg.equals("")) {
            dialogBuilder.setMessage(msg);
        }

        dialogBuilder.setTitle(mUtil.getString(mActivity, R.string.app_name));
        int pushType = 1;
        dialogBuilder.setDialogType(pushType);
        if (!positiveButtonText.equals("")) {
            dialogBuilder.setPositiveButton(positiveButtonText, new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    dialog.dismiss();
                    msgReturProc(1);
                }
            });
        }
        if (!negativeButtonText.equals("")) {
            dialogBuilder.setNegativeButton(negativeButtonText, new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    dialog.dismiss();
                    msgReturProc(2);
                }
            });
        }
        dialogBuilder.setOnCancelListener(new AlertDialog.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {

                dialog.dismiss();
                msgReturProc(2);
            }
        });

        dialog = dialogBuilder.create();
        dialog.setOnDismissListener(this);
        dialog.show();
    }

    private void msgReturProc(int btnResult) {

        switch (pushTypeCode) {
            case "HOME_MEM_INV":
                //    홈 초대 받음
                if (btnResult == 1) {
                    notiCancel();
                    appStart();
                }
                break;
            case "HOME_MEM_REF":
                //    초대했는데 거절 당할 시
                notiCancel();
                break;
            case "HOME_MEM_BAN":
                LogUtil.i(TAG, "msgReturProc : HOME_MEM_BAN!!");
                //    홈 강퇴 받음
                if (btnResult == 1) {
                    notiCancel();
                    if (!appProc.equals("STOP")) {
                        appStart();
                    }
                }
                break;
            case "HOME_MEM_SEL":
                //    홈 자진 탈퇴 받음
                if (btnResult == 1) {
                    notiCancel();
                }
                break;
            case "HOME_DEL":
                //    홈 삭제
                if (btnResult == 1) {
                    notiCancel();
                    if (!appProc.equals("STOP")) {
                        appStart();
                    }
                }
                break;
            case "DVC_CER_REV":
                //    단말 인증 해지 됨
                if (btnResult == 1) {
                    notiCancel();
                    if (!appProc.equals("STOP")) {
                        appStart();
                    }
                }
                break;
            case "MODE_CHG":
                //    홈 모드 변경 시
                notiCancel();
                break;
            case "MODE_CHG_ERR":
                //    홈 모드 변경시 제어 실패
                notiCancel();
                break;
            case "RULE_EXC":
                //    규칙의 액션 결과
                notiCancel();
                break;
            case "RULE_ERR":
                //    규칙의 액션 결과
                notiCancel();
                break;
            case "HOMEHUB_DEL":
                //    홈 허브가 삭제됨
                if (btnResult == 1) {
                    notiCancel();
                    if (!appProc.equals("STOP")) {
                        appStart();
                    }
                }
                break;
            case "DVC_OWN_CHG":
                //    장치 소유주 변경 알림
                if (btnResult == 1) {
                    notiCancel();
                    if (!appProc.equals("STOP")) {
                        appStart();
                    }
                }
                break;
            case "MEM_ALL_OUT":
                //    멤버 All out 시
                if (btnResult == 1) {
                    notiCancel();
                    appStart();
                }
                break;
            case "MEM_ANY_IN":
                //    멤버 Any in 시
                if (btnResult == 1) {
                    notiCancel();
                    appStart();
                }
                break;
            default:
                break;
        }

        onBackPressed();
    }

    /**
     * Notification cancel.
     */
    private void notiCancel() {

        NotificationManager notifier = (NotificationManager)
                mActivity.getSystemService(Context.NOTIFICATION_SERVICE);
        notifier.cancel(Constants.NOTIFICATION_ID);
    }

    /**
     * 푸쉬 타입에 따라 Activity 이동 처리.
     */
    private void appStart() {

        mUtil.callApp_Start(mActivity, pushTypeCode);
    }

    @Override
    public void onDismiss(DialogInterface dialog) {

        onBackPressed();
    }

    /**
     * (외출상태시) 경고 필요한 장치 조회((외출 상태시) 경고가 필요한 장치 노드 목록을 조회한다) 요청.
     */
    private void sendGetDevicesWarningNodes() {

        try {
            HttpSend httpSend;

            httpSend = new HttpSend(mActivity);

            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override
                public void resultResponse(Response result) {

                    resultGetDevicesWarningNodes(result);
                }
            });

            SqlManager sqlManager = new SqlManager();
            SQLiteDatabase db = DatabaseOpenHelper.getInstance(mActivity).getWritableDatabase();
            Cursor cursor = db.rawQuery(sqlManager.qryLoginInfo(), null);
            cursor.moveToFirst();
            while (!cursor.isAfterLast()) {
                mAppConfig.setAuthToken(cursor.getString(cursor.getColumnIndex(TblLoginInfo.LOGIN_PASS)));
                cursor.moveToNext();
            }
            cursor.close();
            db.close();
            httpSend.G_devices_warning_nodes();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * {@link #sendGetDevicesWarningNodes()} 요청 결과.
     *
     * @param response 결과 data
     */
    private void resultGetDevicesWarningNodes(Response response) {

        String tempBody = "";
        try {
            if (response.getStatusCode() == 200) {
                ArrayList<HashMap<String, Object>> alList = mUtil.jsonToArrayListMap(response.getContent());
                if (alList.size() > 0) {
                    ArrayList<HashMap<String, Object>> alTempList = new ArrayList<HashMap<String, Object>>();
                    for (int row = 0; row < alList.size(); row++) {
                        HashMap<String, Object> hmItem;
                        hmItem = alList.get(row);
                        String deviceName = mUtil.null2string(hmItem.get(Constants.KEY_DEVICE_NAME));
                        String cmdclsTypeId = mUtil.null2string(hmItem.get(Constants.KEY_CMDCLS_TYPE_ID));
                        String contentValue = mUtil.null2string(hmItem.get(Constants.KEY_CONTENT_VALUE));

                        String tempValue = mUtil.getStringValues(mActivity, "CMDCLS_TYPE_ID_" + cmdclsTypeId + "_" + contentValue);

                        Boolean isCheck = false;
                        if (alTempList.size() > 0) {
                            for (int row1 = 0; row1 < alTempList.size(); row1++) {
                                HashMap<String, Object> hmItem1;
                                hmItem1 = alTempList.get(row1);
                                if (tempValue.equals(hmItem1.get(Constants.KEY_NAME))) {
                                    String tempDeviceName = mUtil.null2string(hmItem1.get(Constants.KEY_DEVICE_NAME));
                                    int tempDeviceCnt = mUtil.null2int(hmItem1.get(Constants.KEY_CNT));
                                    tempDeviceCnt++;
                                    tempDeviceName += ", " + deviceName;
                                    hmItem1.put(Constants.KEY_CNT, tempDeviceCnt + "");
                                    hmItem1.put(Constants.KEY_DEVICE_NAME, tempDeviceName);
                                    isCheck = true;
                                    break;
                                }
                            }
                        }

                        if (!isCheck) {
                            HashMap<String, Object> hmItem1 = new HashMap<String, Object>();
                            hmItem1.put(Constants.KEY_NAME, tempValue);
                            hmItem1.put(Constants.KEY_CNT, "1");
                            hmItem1.put(Constants.KEY_DEVICE_NAME, deviceName);

                            alTempList.add(hmItem1);
                        }
                    }
                    if (alTempList.size() > 0) {
                        for (int row1 = 0; row1 < alTempList.size(); row1++) {
                            HashMap<String, Object> hmItem1;
                            hmItem1 = alTempList.get(row1);

                            String tempBody1 = "";
                            String name = mUtil.null2string(hmItem1.get(Constants.KEY_NAME));
                            String count = mUtil.null2string(hmItem1.get(Constants.KEY_CNT));
                            String deviceName = mUtil.null2string(hmItem1.get(Constants.KEY_DEVICE_NAME));

                            tempBody1 = "- " + name + " " + count + " : " + deviceName;
                            tempBody += tempBody.equals("") ? tempBody1 : "\n" + tempBody1;
                        }
                    }
                }
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
//                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
//                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));
                tempBody = "";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (dialogCheck) {
            ((TextView) dialog.findViewById(R.id.tvBody))
                    .setText(body + (tempBody.equals("") ? "" : "\n\n" + tempBody));
        } else {
            msgAlert(body + (tempBody.equals("") ? "" : "\n\n" + tempBody));
        }
    }

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            type = msg.what;
            switch (msg.what) {
                case MSG_COM_G_DEVICES_WARNING_NODES:
                    //dialog_show();
                    sendGetDevicesWarningNodes();
                    break;

                default:
                    break;
            }
            return true;
        }
    }
}