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

package com.ntels.kneet.v3.view.dialog;

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 com.ntels.kneet.v3.R;
import com.ntels.kneet.v3.common.AppConfig;
import com.ntels.kneet.v3.common.Constants;
import com.ntels.kneet.v3.common.c_interface.OnDataSendToReslut;
import com.ntels.kneet.v3.common.db.DatabaseOpenHelper;
import com.ntels.kneet.v3.common.db.SQLManager;
import com.ntels.kneet.v3.common.db.entity.TB_LoginInfo;
import com.ntels.kneet.v3.common.http.HttpSend;
import com.ntels.kneet.v3.common.http.Response;
import com.ntels.kneet.v3.common.util.Dlog;
import com.ntels.kneet.v3.common.util.Util;
import com.tsengvn.typekit.TypekitContextWrapper;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
public class PushDialog extends Activity implements OnDismissListener {

    public static Activity act;
    public Util util = new Util();
    public AppConfig appConfig;
    public  String  sBody           = "";
    public  String  sPush_type_code = "";
    public  String  sButton_name    = "";
    public  String  sHomegrp_id     = "";
    public  String  sAppProc        = "";
    private Boolean bDialogCheck    = false;
    private Dialog dialog;

    /*통신 관련*/
    private              ArrayList<HashMap<String, Object>> alTotalList                     = new ArrayList<HashMap<String, Object>>();
    private              int                                iType                           = 0;
    private static final int                                MSG_COM_G_DEVICES_WARNING_NODES = 1;

    @Override protected void attachBaseContext(Context newBase) {

        super.attachBaseContext(TypekitContextWrapper.wrap(newBase));
    }
    @Override protected void onCreate(Bundle savedInstanceState) {

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

        if ( savedInstanceState != null ) {
            sBody = savedInstanceState.getString(Constants.EXTRA_BODY);
            sPush_type_code = savedInstanceState.getString(Constants.EXTRA_PUSH_TYPE_CODE);
            sButton_name = savedInstanceState.getString(Constants.EXTRA_BUTTON_NAME);
            sHomegrp_id = savedInstanceState.getString(Constants.EXTRA_HOMEGRP_ID);
            sAppProc = savedInstanceState.getString(Constants.EXTRA_APP_PROC);
        } else {
            Intent intent = act.getIntent();
            sBody = intent.getStringExtra(Constants.EXTRA_BODY);
            sPush_type_code = intent.getStringExtra(Constants.EXTRA_PUSH_TYPE_CODE);
            sButton_name = intent.getStringExtra(Constants.EXTRA_BUTTON_NAME);
            sHomegrp_id = intent.getStringExtra(Constants.EXTRA_HOMEGRP_ID);
            sAppProc = intent.getStringExtra(Constants.EXTRA_APP_PROC);
        }
        bDialogCheck = false;
        CallMsgAlert(sBody);
    }

    @Override protected void onDestroy() {

        try {
            Dlog.v("onDestroy");

            if ( dialog != null ) {
                if ( dialog.isShowing() ) {
                    dialog.dismiss();
                }
                dialog = null;
            }
            //			RecycleUtils recycleUtils = new RecycleUtils();
            //			recycleUtils.recursiveRecycle(getWindow().getDecorView());
            //			// 메모리 클리어를 위해 액티비티 종료
            //			System.gc();
            bDialogCheck = 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 ) {
            sBody = savedInstanceState.getString(Constants.EXTRA_BODY);
            sPush_type_code = savedInstanceState.getString(Constants.EXTRA_PUSH_TYPE_CODE);
            sButton_name = savedInstanceState.getString(Constants.EXTRA_BUTTON_NAME);
            sHomegrp_id = savedInstanceState.getString(Constants.EXTRA_HOMEGRP_ID);
            sAppProc = savedInstanceState.getString(Constants.EXTRA_APP_PROC);
            CallMsgAlert(sBody);
        }
    }

    @Override protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
        outState.putString(Constants.EXTRA_BODY, sBody);
        outState.putString(Constants.EXTRA_PUSH_TYPE_CODE, sPush_type_code);
        outState.putString(Constants.EXTRA_BUTTON_NAME, sButton_name);
        outState.putString(Constants.EXTRA_HOMEGRP_ID, sHomegrp_id);
        outState.putString(Constants.EXTRA_APP_PROC, sAppProc);
    }

    @Override protected void onNewIntent(Intent intent) {

        super.onNewIntent(intent);
        Dlog.v("onNewIntent");
        overridePendingTransition(0, 0);
        if ( intent != null ) {
            sBody = intent.getStringExtra(Constants.EXTRA_BODY);
            sPush_type_code = intent.getStringExtra(Constants.EXTRA_PUSH_TYPE_CODE);
            sButton_name = intent.getStringExtra(Constants.EXTRA_BUTTON_NAME);
            sHomegrp_id = intent.getStringExtra(Constants.EXTRA_HOMEGRP_ID);
            sAppProc = intent.getStringExtra(Constants.EXTRA_APP_PROC);
            if ( dialog != null ) {
                if ( dialog.isShowing() ) {
                    bDialogCheck = true;
                } else {
                    bDialogCheck = false;
                }
            } else {
                bDialogCheck = false;
            }
            CallMsgAlert(sBody);
        }
    }

    /**
     * <PRE>
     * 1. MethodName: onResume
     * 2. ClassName :
     * 3. Comment   : onResume
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    @Override public void onResume() {

        super.onResume();
    }

    public void CallMsgAlert(String sMsg) {

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

            ComHandler.sendMessageDelayed(ComHandler.obtainMessage(MSG_COM_G_DEVICES_WARNING_NODES), 10);
        } else {
            if ( bDialogCheck ) {
                ((TextView) dialog.findViewById(R.id.tvBody)).setText(sBody);
            } else {
                MsgAlert(sBody);
            }
        }
    }
    /**
     * <PRE>
     * 1. MethodName: MsgAlert
     * 2. ClassName :
     * 3. Comment   : message box dialog
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void MsgAlert(String sMsg) {

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

        int iPushType = 1;

        Dialog_Custom.Builder dialog_builder;
        dialog_builder = new Dialog_Custom.Builder(act);
        if ( iMsgNo != 0 ) {
            dialog_builder.setErrNo("MSG" + iMsgNo);
        }
        if ( !sMsg.equals("") ) {
            dialog_builder.setMessage(sMsg);
        }

        dialog_builder.setTitle(util.getString(act, R.string.app_name));
        dialog_builder.setDialogType(iPushType);
        if ( !sPositiveButtonText.equals("") ) {
            dialog_builder.setPositiveButton(sPositiveButtonText, new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

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

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

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

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

    private void MsgReturProc(int iBtnResult) {

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

        onBackPressed();
    }

    private void notiCancel() {

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

    private void appStart() {

        //        Intent intent = new Intent(Intent.ACTION_VIEW);
        //        intent.addCategory(Intent.CATEGORY_DEFAULT);
        //        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        //        intent.setData(Uri.parse(util.getPreferences(this, Constants.EXTRA_APPSTART_ID) + "://start?type=" + sPush_type_code));
        //        act.startActivity(intent);
        util.callApp_Start(act, sPush_type_code);
    }

    @Override public void onDismiss(DialogInterface dialog) {

        onBackPressed();
    }

    private void sendAppExitLocalBoradCast() {

        //        Intent intent = new Intent(KneetMessageLocalBroadCast.INTENT_ACTION);
        //        // add data
        //        intent.putExtra(KneetMessageLocalBroadCast.INTENT_NAME_TYPE, KneetMessageLocalBroadCast.INTENT_AUCTION_APP_EXIT);
        //        intent.putExtra(KneetMessageLocalBroadCast.INTENT_DUPLICATE_LOGIN, true);
        //        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        //        // sendNotification(message);
    }

    Handler ComHandler = new Handler(new IncomingHandlerCallBack());

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override public boolean handleMessage(Message msg) {

            iType = msg.what;
            switch (msg.what) {
                case MSG_COM_G_DEVICES_WARNING_NODES:
                    //dialog_show();
                    send_G_devices_warning_nodes();
                    break;

                default:
                    break;
            }
            return true;
        }
    }

    /**
     * <PRE>
     * 1. MethodName: send_G_devices_warning_nodes
     * 2. ClassName :
     * 3. Comment   : [Send][GET](외출 상태시) 경고 필요한 장치 조회((외출 상태시) 경고가 필요한 장치 노드 목록을 조회한다.)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void send_G_devices_warning_nodes() {

        try {
            HttpSend httpSend;

            //            httpSend = new HttpSend(act, !swipeRefreshLayout.isRefreshing());
            httpSend = new HttpSend(act);

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

                    result_G_devices_warning_nodes(result);
                }
            });

            SQLManager sqlManager = new SQLManager();
            SQLiteDatabase db = DatabaseOpenHelper.getInstance(act).getWritableDatabase();
            Cursor cursor = db.rawQuery(sqlManager.QryLoginInfo(), null);
            cursor.moveToFirst();
            while (!cursor.isAfterLast()) {
                appConfig.setAuth_Token(cursor.getString(cursor.getColumnIndex(TB_LoginInfo.LOGIN_PASS)));
                cursor.moveToNext();
            }
            cursor.close();
            db.close();
            httpSend.G_devices_warning_nodes();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * <PRE>
     * 1. MethodName: result_G_devices_warning_nodes
     * 2. ClassName :
     * 3. Comment   : [Result][GET](외출 상태시) 경고 필요한 장치 조회((외출 상태시) 경고가 필요한 장치 노드 목록을 조회한다.)
     * 4. Developer : 최진오
     * 5. Created   : 2015. 10.
     * </PRE>
     */
    private void result_G_devices_warning_nodes(Response rpResult) {

        String sTempBody = "";
        try {
            if ( rpResult.getStatusCode() == 200 ) {
                ArrayList<HashMap<String, Object>> alList = util.jsonToArrayListMap(rpResult.getContent());
                if ( alList.size() > 0 ) {
                    ArrayList<HashMap<String, Object>> alTempList = new ArrayList<HashMap<String, Object>>();
                    for ( int iRow = 0; iRow < alList.size(); iRow++ ) {
                        HashMap<String, Object> hmItem = new HashMap<String, Object>();
                        hmItem = alList.get(iRow);
                        String sHTTP_device_id = util.null2string(hmItem.get(Constants.HTTP_device_id));
                        String sHTTP_device_name = util.null2string(hmItem.get(Constants.HTTP_device_name));
                        String sHTTP_node_id = util.null2string(hmItem.get(Constants.HTTP_node_id));
                        String sHTTP_node_name = util.null2string(hmItem.get(Constants.HTTP_node_name));
                        String sHTTP_cmdcls_type_id = util.null2string(hmItem.get(Constants.HTTP_cmdcls_type_id));
                        int iCmdcls_Type = util.null2int(hmItem.get(Constants.HTTP_cmdcls_type_id));
                        String sHTTP_cmdcls_code = util.null2string(hmItem.get(Constants.HTTP_cmdcls_code));
                        String sHTTP_cmdcls_type_system_name = util.null2string(hmItem.get(Constants.HTTP_cmdcls_type_system_name));
                        String sHTTP_content_value = util.null2string(hmItem.get(Constants.HTTP_content_value));

                        //                        String sSelect = util.getStringValues(act, "CMDCLS_TYPE_ID_" + sHTTP_cmdcls_type_id + "_BG_DEFAULT");
                        String sTempValue = util.getStringValues(act, "CMDCLS_TYPE_ID_" + sHTTP_cmdcls_type_id + "_" + sHTTP_content_value);

                        Boolean bCheck = false;
                        if ( alTempList.size() > 0 ) {
                            for ( int iRow1 = 0; iRow1 < alTempList.size(); iRow1++ ) {
                                HashMap<String, Object> hmItem1 = new HashMap<String, Object>();
                                hmItem1 = alTempList.get(iRow1);
                                if ( sTempValue.equals(hmItem1.get(Constants.HTTP_name)) ) {
                                    String sTempDeviceName = util.null2string(hmItem1.get(Constants.HTTP_device_name));
                                    int iTempDeviceCnt = util.null2int(hmItem1.get(Constants.HTTP_cnt));
                                    iTempDeviceCnt++;
                                    sTempDeviceName += ", " + sHTTP_device_name;
                                    //                                    sTempDeviceName += sTempDeviceName.equals("") ? sHTTP_device_name : ", " + sHTTP_device_name;
                                    hmItem1.put(Constants.HTTP_cnt, iTempDeviceCnt + "");
                                    hmItem1.put(Constants.HTTP_device_name, sTempDeviceName);
                                    bCheck = true;
                                    break;
                                }
                            }
                        }

                        if ( !bCheck ) {
                            HashMap<String, Object> hmItem1 = new HashMap<String, Object>();
                            hmItem1.put(Constants.HTTP_name, sTempValue);
                            hmItem1.put(Constants.HTTP_cnt, "1");
                            hmItem1.put(Constants.HTTP_device_name, sHTTP_device_name);

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

                            String sTempBody1 = "";
                            String sHTTP_name = util.null2string(hmItem1.get(Constants.HTTP_name));
                            String sHTTP_cnt = util.null2string(hmItem1.get(Constants.HTTP_cnt));
                            String sHTTP_device_name = util.null2string(hmItem1.get(Constants.HTTP_device_name));

                            sTempBody1 = "- " + sHTTP_name + " " + sHTTP_cnt + " : " + sHTTP_device_name;
                            sTempBody += sTempBody.equals("") ? sTempBody1 : "\n" + sTempBody1;
                        }
                    }
                }
            } else {
                JSONObject joResult = new JSONObject(rpResult.getContent());
                Dlog.v(joResult.toString());
                String sERR_CODE = util.null2string(joResult.get(Constants.HTTP_err_code));
                String sERR_MSG = util.null2string(joResult.get(Constants.HTTP_err_msg));
                sTempBody = "";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            //            customDialog.MsgAlert(act, Constants.MSG807);
        }
        if ( bDialogCheck ) {
            ((TextView) dialog.findViewById(R.id.tvBody)).setText(sBody + (sTempBody.equals("") ? "" : "\n\n" + sTempBody));
        } else {
            MsgAlert(sBody + (sTempBody.equals("") ? "" : "\n\n" + sTempBody));
        }
    }
}