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

package com.ntels.onecable.view.rules;

import com.kyleduo.switchbutton.SwitchButton;
import com.ntels.onecable.R;
import com.ntels.onecable.common.AppConfig;
import com.ntels.onecable.common.Constants;
import com.ntels.onecable.common.c_interface.OnDataSendToReslut;
import com.ntels.onecable.common.http.HttpSend;
import com.ntels.onecable.common.http.Response;
import com.ntels.onecable.common.util.Dlog;
import com.ntels.onecable.common.util.Util;
import com.ntels.onecable.common.widget.CustomActivity;
import com.ntels.onecable.view.dialog.CustomDialog;
import com.ntels.onecable.view.dialog.DialogCustomList;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * <pre>
 * 1. ClassName :   RulesDetail
 * 2. FileName  :   RulesDetail.java
 * 3. Package   :   com.ntels.onecable.view.rules
 * 4. Date      :   2016-11-28
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class RulesDetail extends CustomActivity implements View.OnClickListener,
        CustomDialog.OnMsgAlterToResult {

    private static final int MSG_COM_G_RULES_HOMEGRP_RULE_ID = 1;
    private static final int MSG_COM_D_RULES_HOMEGRP_RULE_ID = 2;
    private static final int MSG_COM_P_RULES_HOMEGRP_RULE_ID_STATUS = 3;
    String triggers;
    String actions;
    String conditions;
    String rulesDetailJson = "";
    Handler comHandler = new Handler(new IncomingHandlerCallBack());
    private DecimalFormat decimalFormat = new DecimalFormat("00");
    private String ruleId = "";
    private String ruleUseYn = "N";
    private ArrayList<HashMap<String, Object>> conditionList = new ArrayList<>();
    private ArrayList<HashMap<String, Object>> actionList = new ArrayList<>();
    private ArrayList<HashMap<String, Object>> triggerList = new ArrayList<>();
    private SwipeRefreshLayout swipeRefreshLayout;
    private boolean loading = false;
    private Boolean isReload = false;
    /*통신 관련*/
    private int type = 0;
    /*공통*/
    private Activity mActivity;
    private AppConfig mAppConfig;
    private Intent intent;
    private Util mUtil = new Util();
    private CustomDialog customDialog = new CustomDialog();
    private boolean mIsFromUser = true;
    @BindView(R.id.sbOnOff)
    SwitchButton mStateOnOff;
    @BindView(R.id.tvAlarmMsg)
    TextView mAlarmMsg;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        mActivity = RulesDetail.this;
        mAppConfig = (AppConfig) mActivity.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);

        View viewToLoad = LayoutInflater.from(mActivity).inflate(R.layout.rules_detail, null);
        this.setContentView(viewToLoad);

        ButterKnife.bind(this);

        if (null != getIntent()) {
            Intent intent = getIntent();
            ruleId = intent.getStringExtra(Constants.EXTRA_MEMBER_RULE_ID);
        }

        setToolbar();
        setDisp();
    }

    /**
     * 툴바 셋팅.
     */
    private void setToolbar() {

        Toolbar toolbar = (Toolbar) mActivity.findViewById(R.id.toolbar);
        mUtil.setKeyboardHide(mActivity, toolbar);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitle1).setVisibility(View.VISIBLE);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitle2).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitleDivider).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitle3).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.tvToolbarTitle4).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
        mUtil.getTextView(toolbar, R.id.btnToolbarMore).setVisibility(View.VISIBLE);

        mUtil.getTextView(toolbar, R.id.tvToolbarTitle1)
                .setText(mUtil.getString(mActivity, R.string.layout_rules_detail_01));

        mUtil.getView(toolbar, R.id.btnToolbarMore).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                ArrayList<HashMap<String, Object>> alMenuList = new ArrayList<HashMap<String, Object>>();
                alMenuList.add(mUtil.getPopMenu(6));

                if (mAppConfig.getCtrtGroupGradeCode().equals("MAS")) {
                    alMenuList.add(mUtil.getPopMenu(19));
                    alMenuList.add(mUtil.getPopMenu(18));
                }
                msgAlertList(alMenuList);
            }
        });
    }

    /**
     * UI display.
     */
    private void setDisp() {

//        mUtil.getView(mActivity, R.id.btnOnOff).setOnClickListener(this);
        mStateOnOff.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                if (!mIsFromUser) {
                    mIsFromUser = true;
                    return;
                }

                if (ruleUseYn.equals("Y")) {
                    mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG808), Toast.LENGTH_SHORT);
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(
                            MSG_COM_P_RULES_HOMEGRP_RULE_ID_STATUS), Constants.HANDLER_DELAY_MILLIS);
                } else if (ruleUseYn.equals("N")) {
                    mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG809), Toast.LENGTH_SHORT);
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(
                            MSG_COM_P_RULES_HOMEGRP_RULE_ID_STATUS), Constants.HANDLER_DELAY_MILLIS);
                } else if (ruleUseYn.equals("X")) {
                    customDialog.msgAlert(mActivity, Constants.MSG818, R.string.MSG_TITLE_000,
                            mUtil.getString(mActivity, R.string.MSG_BTN_EDIT),
                            mUtil.getString(mActivity, R.string.MSG_BTN_CANCEL));
                }
            }
        });
        mUtil.getView(mActivity, R.id.llBtn1).setOnClickListener(this);

        swipeRefreshLayout = (SwipeRefreshLayout) mActivity.findViewById(R.id.swiperefreshlayou);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_red_light,
                android.R.color.holo_green_light, android.R.color.holo_blue_bright,
                android.R.color.holo_orange_light);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                if (!loading) {
                    loading = true;
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_RULES_HOMEGRP_RULE_ID),
                            Constants.HANDLER_DELAY_MILLIS);
                }
            }
        });
        if (mAppConfig.getCtrtGroupGradeCode().equals("MAS")) {
            mUtil.getView(mActivity, R.id.llState).setVisibility(View.VISIBLE);
        } else {
            mUtil.getView(mActivity, R.id.llState).setVisibility(View.GONE);
        }
        comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_RULES_HOMEGRP_RULE_ID), Constants.HANDLER_DELAY_MILLIS);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.llBtn1:
                onBackPressed();
                break;

            /*case R.id.btnOnOff:
                if (ruleUseYn.equals("Y")) {
                    mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG808), Toast.LENGTH_SHORT);
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(
                            MSG_COM_P_RULES_HOMEGRP_RULE_ID_STATUS), Constants.HANDLER_DELAY_MILLIS);
                } else if (ruleUseYn.equals("N")) {
                    mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG809), Toast.LENGTH_SHORT);
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(
                            MSG_COM_P_RULES_HOMEGRP_RULE_ID_STATUS), Constants.HANDLER_DELAY_MILLIS);
                } else if (ruleUseYn.equals("X")) {
                    customDialog.msgAlert(mActivity, Constants.MSG818, R.string.MSG_TITLE_000,
                            mUtil.getString(mActivity, R.string.MSG_BTN_EDIT),
                            mUtil.getString(mActivity, R.string.MSG_BTN_CANCEL));
                }
                break;*/
            default:
                break;
        }
    }

    /**
     * 홈 규칙 상태 변경(해당 규칙의 상태를 변경한다) 요청.
     */
    private void sendPutRuleStatus() {
        try {
            HttpSend httpSend;

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

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

            mIsFromUser = false;
            if (ruleUseYn.equals("Y")) {
//                mUtil.getButton(mActivity, R.id.btnOnOff).setSelected(true);
                mStateOnOff.setChecked(true);
                mUtil.getView(mActivity, R.id.tvNotice).setVisibility(View.GONE);
            } else if (ruleUseYn.equals("N")) {
                mStateOnOff.setChecked(false);
                mUtil.getView(mActivity, R.id.tvNotice).setVisibility(View.GONE);
            }
            String statusCode = "";

            if (ruleUseYn.equals("Y")) {
                statusCode = "03";
            } else if (ruleUseYn.equals("N")) {
                statusCode = "02";
            }
            httpSend.putRuleStatus(ruleId, statusCode);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 홈 규칙 상태 변경(해당 규칙의 상태를 변경한다) 요청 결과.
     *
     * @param result 결과 data
     */
    private void resultPutRuleStatus(Response result) {
        try {
            if (result.getStatusCode() == 200) {
                isReload = true;
                comHandler.sendMessageDelayed(comHandler.obtainMessage(
                        MSG_COM_G_RULES_HOMEGRP_RULE_ID), Constants.HANDLER_DELAY_MILLIS);
            } else {
                JSONObject joResult = new JSONObject(result.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));

                if (resultCode.equals("401")) {
                    customDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                } else {
                    customDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    /**
     * 홈 규칙 상세 조회(해당 규칙의 정보를 상세 조회한다) 요청.
     */
    private void sendGetRuleDetail() {

        try {
            HttpSend httpSend;

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

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

                    resultGetRuleDetail(result);
                }
            });
            httpSend.getRuleDetail(ruleId);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 홈 규칙 상세 조회(해당 규칙의 정보를 상세 조회한다) 요청 결과.
     *
     * @param result 결과 data.
     */
    private void resultGetRuleDetail(Response result) {

        try {
            if (result.getStatusCode() == 200) {
                rulesDetailJson = result.getContent();

                setRulesJasonInit(result.getContent());
                loading = false;
                swipeRefreshLayout.setRefreshing(false);
            } else {
                JSONObject joResult = new JSONObject(result.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));

                if (resultCode.equals("401")) {
                    customDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                } else if (resultCode.equals("401-106")) {
                    customDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                } else {
                    customDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    /**
     * 홈 규칙 삭제(해당 규칙을 삭제한다) 요청.
     */
    private void sendDeleteRule() {

        try {
            HttpSend httpSend;

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

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

                    resultDeleteRule(result);
                }
            });
            httpSend.deleteRule(ruleId);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 홈 규칙 삭제(해당 규칙을 삭제한다) 요청 결과.
     *
     * @param result 결과 data
     */
    private void resultDeleteRule(Response result) {

        try {
            if (result.getStatusCode() == 200) {
                isReload = true;
                mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG857), Toast.LENGTH_SHORT);
                intent = new Intent();
                intent.putExtra(Constants.EXTRA_RELOAD_FLAG, isReload);
                mActivity.setResult(RESULT_OK, intent);
                finish();
            } else {
                JSONObject joResult = new JSONObject(result.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));

                if (resultCode.equals("401")) {
                    customDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                } else if (resultCode.equals("401-106")) {
                    customDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                } else {
                    customDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    @Override
    public void onBackPressed() {

        intent = new Intent();
        intent.putExtra(Constants.EXTRA_RELOAD_FLAG, isReload);
        mActivity.setResult(RESULT_CANCELED, intent);
        finish();
        return;
    }

    /**
     * 메뉴 선택 시 처리.
     *
     * @param list 메뉴 리스트
     */
    private void msgAlertList(ArrayList<HashMap<String, Object>> list) {

        try {
            DialogCustomList.Builder dialogListBuilder = new DialogCustomList.Builder(mActivity);
            dialogListBuilder.setList(list);
            dialogListBuilder.setPositiveButton(new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    dialog.dismiss();
                    Dlog.v("which = " + which);
                    switch (which) {
                        case 1:
                            break;
                        case 2:
                            break;
                        case 3:
                            break;
                        case 4:
                            break;
                        case 5:
                            break;
                        case 6:
                            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_RULES_HOMEGRP_RULE_ID),
                                    Constants.HANDLER_DELAY_MILLIS);
                            break;
                        case 7:
                            break;
                        case 8:
                            break;
                        case 9:
                            break;
                        case 10:
                            break;
                        case 11:
                            break;
                        case 12:
                            break;
                        case 15:
                            break;
                        case 16:
                            break;
                        case 17:
                            break;
                        case 18:
                            customDialog.msgAlert(mActivity, Constants.MSG810, R.string.MSG_TITLE_003,
                                    mUtil.getString(mActivity, R.string.layout_delete),
                                    mUtil.getString(mActivity, R.string.layout_cancel));
                            break;
                        case 19:
                            Intent intent = new Intent(mActivity, RulesEdit.class);
                            intent.putExtra(Constants.EXTRA_CALL_TYPE, "2");
                            intent.putExtra(Constants.EXTRA_MEMBER_RULE_ID, ruleId);
                            mUtil.callActivityForResult(mActivity, intent, Constants.ACT_RULES_EDIT);
                            break;
                        default:
                            break;
                    }
                }
            });
            dialogListBuilder.setNegativeButton(new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    Dlog.v("which = " + which);
                    dialog.dismiss();
                }
            });
            dialogListBuilder.create().show();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void resultCustomDialogResponse(int msgId, int btnResult) {

        switch (msgId) {

            case Constants.MSG998:
                mUtil.callApp_Start(mActivity, "LOGOUT");
                break;
            case Constants.MSG997:
                mUtil.callApp_Start(mActivity, "HOME_RELOAD");
                break;
            case Constants.MSG807:
                if (btnResult == 1) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(type), Constants.HANDLER_DELAY_MILLIS);
                }
                break;
            case Constants.MSG810:
                if (btnResult == 1) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_D_RULES_HOMEGRP_RULE_ID),
                            Constants.HANDLER_DELAY_MILLIS);
                }
                break;
            case Constants.MSG818:
                if (btnResult == 1) {
                    Intent intent = new Intent(mActivity, RulesEdit.class);
                    intent.putExtra(Constants.EXTRA_CALL_TYPE, "2");
                    intent.putExtra(Constants.EXTRA_MEMBER_RULE_ID, ruleId);
                    mUtil.callActivityForResult(mActivity, intent, Constants.ACT_RULES_EDIT);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == mActivity.RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_RULES_EDIT:
                    if (data == null) {
                        return;
                    }
                    isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (isReload) {
                        comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_RULES_HOMEGRP_RULE_ID),
                                Constants.HANDLER_DELAY_MILLIS);
                    }
                    break;
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_RULES_EDIT:
                    if (data == null) {
                        return;
                    }
                    isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (isReload) {
                        comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_RULES_HOMEGRP_RULE_ID),
                                Constants.HANDLER_DELAY_MILLIS);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * Rule json parsing.
     *
     * @param content 파싱 할 json string
     */
    void setRulesJasonInit(String content) {

        try {
            JSONObject joResult = new JSONObject(content);

            ruleId = mUtil.null2string(joResult.get(Constants.KEY_RULE_ID));
            String ruleName = mUtil.null2string(joResult.get(Constants.KEY_RULE_NAME));
            mUtil.getTextView(mActivity, R.id.tvRulesName).setText(ruleName);

            if (joResult.has(Constants.KEY_LATEST_EXECUTION_DATETIME)) {
                mUtil.getView(mActivity, R.id.llLastActionTime).setVisibility(View.VISIBLE);
                String latestExecutionDatetime = mUtil.null2string(joResult.get(Constants.KEY_LATEST_EXECUTION_DATETIME));
                if (!"".equals(latestExecutionDatetime)) {
                    mUtil.getTextView(mActivity, R.id.tvLastActionTime).setText(mUtil.UTCtoLocal5(latestExecutionDatetime));
                }
            } else {
                mUtil.getView(mActivity, R.id.llLastActionTime).setVisibility(View.GONE);
                mUtil.getTextView(mActivity, R.id.tvLastActionTime).setText("");
            }

            ruleUseYn = mUtil.null2string(joResult.get(Constants.KEY_USE_YN));

//            mUtil.getButton(mActivity, R.id.btnOnOff).setSelected(false);
            mIsFromUser = false;
            if (ruleUseYn.equals("Y")) {
//                mUtil.getButton(mActivity, R.id.btnOnOff).setSelected(true);
                mStateOnOff.setChecked(true);
                mUtil.getView(mActivity, R.id.tvNotice).setVisibility(View.GONE);
            } else if (ruleUseYn.equals("N")) {
                mStateOnOff.setChecked(false);
                mUtil.getView(mActivity, R.id.tvNotice).setVisibility(View.GONE);
            } else if (ruleUseYn.equals("X")) {
                mStateOnOff.setChecked(false);
                mUtil.getView(mActivity, R.id.tvNotice).setVisibility(View.VISIBLE);
            }

            conditions = mUtil.null2empty(joResult.get(Constants.KEY_CONDITIONS)).toString();
            triggers = mUtil.null2empty(joResult.get(Constants.KEY_TRIGGERS)).toString();
            actions = mUtil.null2empty(joResult.get(Constants.KEY_ACTIONS)).toString();

            setDispConditionsInit();
            setDispTriggersInit();
            setDispActionsInit();
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    /**
     * Triggers data initialize.
     */
    void setDispTriggersInit() {

        Dlog.v("triggers=", triggers);
        triggerList.clear();
        triggerList = mUtil.jsonToArrayListMap(triggers);
        setDispTriggers();
    }

    /**
     * Triggers data display.
     */
    void setDispTriggers() {

        Dlog.v("alList_Triggers1 = ", triggerList.toString());
        if (triggerList.size() > 0) {
            mUtil.getLinearLayout(mActivity, R.id.llTrigger).setVisibility(View.VISIBLE);
            mUtil.getLinearLayout(mActivity, R.id.llTriggerBody).removeAllViews();

            //현재로써는 트리거는 단일임 나중에 멀티일때 풀어야 함
            //            for ( int row = 0; row < triggerList.size(); row++ ) {
            int row = 0;
            HashMap<String, Object> hmTemp = new HashMap<String, Object>();
            hmTemp = triggerList.get(row);
            LinearLayout childView = (LinearLayout) View.inflate(
                    this, R.layout.row_rules_triggers_list, null);
            mUtil.getView(childView, R.id.btnRowDelete).setVisibility(View.GONE);

            String itemName = "";//mUtil.null2string(hmTemp.get(Constants.KEY_item_name));
            String itemSubTypeCode = mUtil.null2string(hmTemp.get(Constants.KEY_ITEM_SUB_TYPE_CODE));

            ArrayList<HashMap<String, Object>> itemSubList = new ArrayList<HashMap<String, Object>>();
            if (!mUtil.null2string(hmTemp.get(Constants.KEY_ITEM_SUB)).equals("")) {
                itemSubList = (ArrayList<HashMap<String, Object>>) hmTemp.get(Constants.KEY_ITEM_SUB);
            }
            if (itemSubList != null) {
                int row1 = 0;
                if (itemSubTypeCode.equals("05")) {
                    //time
                    itemName = mUtil.getString(mActivity, R.string.layout_rules_triggers_select_02);
                    String httpHour = mUtil.null2string(itemSubList.get(row1).get(Constants.KEY_HOUR));
                    String minute = mUtil.null2string(itemSubList.get(row1).get(Constants.KEY_MINUTE));
                    String[] time = mUtil.UTCtoLocal6(httpHour + minute);
                    String ampm = (mUtil.str2int(time[0]) >= 12
                            ? mUtil.getString(mActivity, R.string.layout_pm) : mUtil.getString(mActivity, R.string.layout_am));
                    String hour = (mUtil.str2int(time[0]) >= 12
                            ? decimalFormat.format((mUtil.str2int(time[0]) - 12)) : time[0]);
                    String dayOfWeek = getAlListConditions(1);

                    if (mAppConfig.getLanguage_Id().equals("ko")) {
                        mUtil.getTextView(childView, R.id.tvRowTitle).setText(ampm + " " + hour
                                + mUtil.getString(mActivity, R.string.layout_hour) + " " + time[1] + mUtil.getString(mActivity,
                                R.string.layout_minute));
                    } else {
                        mUtil.getTextView(childView, R.id.tvRowTitle).setText(hour
                                + mUtil.getString(mActivity, R.string.layout_hour)
                                + time[1]
                                + mUtil.getString(mActivity, R.string.layout_minute)
                                + " "
                                + ampm);
                    }

                    mUtil.getTextView(childView, R.id.tvRowBody).setText(dayOfWeek);
                    mUtil.getTextView(childView, R.id.tvRowState).setVisibility(View.GONE);

                    mUtil.setImage(R.drawable.img_rule_icon_time,
                            mUtil.getImageView(childView, R.id.ivRowIcon));
                } else if (itemSubTypeCode.equals("32")) {
                    //sun
                    itemName = mUtil.getString(mActivity, R.string.layout_rules_triggers_select_03);
                    String sourceName = mUtil.null2string(itemSubList.get(row1)
                            .get(Constants.KEY_SOURCE_NAME));
                    String sourceSubName = mUtil.null2string(itemSubList.get(row1)
                            .get(Constants.KEY_SOURCE_SUB_NAME));
                    String dayOfWeek = getAlListConditions(1);

                    mUtil.getTextView(childView, R.id.tvRowTitle).setText(sourceSubName);

                    mUtil.getTextView(childView, R.id.tvRowBody).setText(sourceName + "/" + dayOfWeek);
                    mUtil.getTextView(childView, R.id.tvRowState).setVisibility(View.GONE);

                    mUtil.setImage(R.drawable.img_rule_icon_sunrises,
                            mUtil.getImageView(childView, R.id.ivRowIcon));
                } else if (itemSubTypeCode.equals("31")) {
                    //더울 때 /추울때
                    itemName = mUtil.getString(mActivity, R.string.layout_rules_triggers_select_04);
                    String sourceName = mUtil.null2string(itemSubList.get(row1)
                            .get(Constants.KEY_SOURCE_NAME));
                    String conditionTypeCode = mUtil.null2string(itemSubList.get(row1)
                            .get(Constants.KEY_CONDITION_TYPE_CODE));
                    String cmdclsValue = mUtil.null2string(itemSubList.get(row1)
                            .get(Constants.KEY_CMDCLS_VALUE));
                    String dayOfWeek = getAlListConditions(1);

                    String tempMsg = "";
                    if (conditionTypeCode.equals("02")) {
                        tempMsg = mUtil.getString(mActivity, R.string.layout_rules_triggers_hot_03);
                    } else if (conditionTypeCode.equals("04")) {
                        tempMsg = mUtil.getString(mActivity, R.string.layout_rules_triggers_hot_02);
                    }

                    mUtil.getTextView(childView, R.id.tvRowTitle).setText(tempMsg);

                    mUtil.getTextView(childView, R.id.tvRowBody).setText(sourceName + "/" + cmdclsValue
                            + mUtil.getString(mActivity, R.string.layout_temperature1) + "/" + dayOfWeek);
                    mUtil.getTextView(childView, R.id.tvRowState).setVisibility(View.GONE);

                    mUtil.setImage(R.drawable.img_rule_icon_temperature,
                            mUtil.getImageView(childView, R.id.ivRowIcon));
                } else if (itemSubTypeCode.equals("01")) {
                    //상태가 변할때
                    itemName = mUtil.getString(mActivity, R.string.layout_rules_triggers_select_01);
                    String sourceName = mUtil.null2string(itemSubList.get(row1)
                            .get(Constants.KEY_SOURCE_NAME));
                    String sourceSubName = mUtil.null2string(itemSubList.get(row1)
                            .get(Constants.KEY_SOURCE_SUB_NAME));
                    String deleteYn = mUtil.null2string(itemSubList.get(row1)
                            .get(Constants.KEY_DELETE_YN));

                    if (deleteYn.equals("Y")) {
                        mUtil.getTextView(childView, R.id.tvRowTitle).setText(mUtil.setSpCenterLine(mActivity, sourceName));
                    } else {
                        mUtil.getTextView(childView, R.id.tvRowTitle).setText(sourceName);
                    }
                    mUtil.getTextView(childView, R.id.tvRowBody).setText(sourceSubName);
                    mUtil.getTextView(childView, R.id.tvRowState).setVisibility(View.VISIBLE);
                    String conditionTypeCode = mUtil.null2string(itemSubList.get(row1).get(Constants.KEY_CONDITION_TYPE_CODE));
                    String conditionTypeCodeName = mUtil.null2string(itemSubList.get(row1).get(Constants.KEY_CONDITION_TYPE_CODE_NAME));
                    String cmdclsValue = mUtil.null2string(itemSubList.get(row1).get(Constants.KEY_CMDCLS_VALUE));
                    String cmdclsValueMsg = mUtil.null2string(itemSubList.get(row1).get(Constants.KEY_CMDCLS_VALUE_MSG));
                    String unit = mUtil.null2string(itemSubList.get(row1).get(Constants.KEY_UNIT));
                    mUtil.getTextView(childView, R.id.tvRowState).setText((cmdclsValueMsg.equals("")
                            ? cmdclsValue : cmdclsValueMsg) + unit + (conditionTypeCode.equals("01") ? "" : conditionTypeCodeName));

                    String imgaeFileName = mUtil.null2string(itemSubList.get(row1)
                            .get(Constants.KEY_IMAGE_FILE_NAME));
                    mUtil.setImage(mActivity, imgaeFileName, mUtil.getImageView(childView, R.id.ivRowIcon));
                }
            }
            mUtil.getTextView(mActivity, R.id.tvTriggerTitle).setText(itemName);
            mUtil.getLinearLayout(mActivity, R.id.llTriggerBody).addView(childView);
            //            }
        } else {
            mUtil.getLinearLayout(mActivity, R.id.llTrigger).setVisibility(View.GONE);
        }
    }

    /**
     * Actions data initialize.
     */
    void setDispActionsInit() {

        Dlog.v("actions=", actions);
        actionList.clear();
        actionList = mUtil.jsonToArrayListMap(actions);
        setDispActions();
    }

    /**
     * Actions data display.
     */
    void setDispActions() {

        Dlog.v("alList_Actions1 = ", actionList.toString());
        if (actionList.size() > 0) {

            mUtil.getLinearLayout(mActivity, R.id.llAction).setVisibility(View.GONE);
            mUtil.getLinearLayout(mActivity, R.id.llActionBody).removeAllViews();

            mUtil.getLinearLayout(mActivity, R.id.llAlarm).setVisibility(View.GONE);
//            mUtil.getLinearLayout(mActivity, R.id.llAlramBody).removeAllViews();
            for (int row = 0; row < actionList.size(); row++) {
                HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                hmTemp = actionList.get(row);

                String itemSubTypeCode = mUtil.null2string(hmTemp.get(Constants.KEY_ITEM_SUB_TYPE_CODE));

                ArrayList<HashMap<String, Object>> itemSubList = new ArrayList<HashMap<String, Object>>();
                if (!mUtil.null2string(hmTemp.get(Constants.KEY_ITEM_SUB)).equals("")) {
                    itemSubList = (ArrayList<HashMap<String, Object>>) hmTemp.get(Constants.KEY_ITEM_SUB);
                }
                if (itemSubList != null) {
                    if (itemSubTypeCode.equals("01")) {
                        mUtil.getLinearLayout(mActivity, R.id.llAction).setVisibility(View.VISIBLE);
                        for (int row1 = 0; row1 < itemSubList.size(); row1++) {
                            LinearLayout childView = (LinearLayout) View.inflate(
                                    this, R.layout.row_rules_actions_list, null);
                            mUtil.getView(childView, R.id.btnRowDelete).setVisibility(View.GONE);

                            String sourceName = mUtil.null2string(itemSubList.get(row1)
                                    .get(Constants.KEY_SOURCE_NAME));
                            String sourceSubName = mUtil.null2string(itemSubList.get(row1)
                                    .get(Constants.KEY_SOURCE_SUB_NAME));
                            String deleteYn = mUtil.null2string(itemSubList.get(row1)
                                    .get(Constants.KEY_DELETE_YN));

                            if (deleteYn.equals("Y")) {
                                mUtil.getTextView(childView, R.id.tvRowTitle).setText(
                                        mUtil.setSpCenterLine(mActivity, sourceName));
                            } else {
                                mUtil.getTextView(childView, R.id.tvRowTitle).setText(sourceName);
                            }
                            mUtil.getTextView(childView, R.id.tvRowBody).setText(sourceSubName);
                            mUtil.getTextView(childView, R.id.tvRowState).setVisibility(View.VISIBLE);
                            String conditionTypeCode = mUtil.null2string(itemSubList.get(row1)
                                    .get(Constants.KEY_CONDITION_TYPE_CODE));
                            String conditionTypeCodeName = mUtil.null2string(itemSubList.get(row1)
                                    .get(Constants.KEY_CONDITION_TYPE_CODE_NAME));
                            String cmdclsValue = mUtil.null2string(itemSubList.get(row1)
                                    .get(Constants.KEY_CMDCLS_VALUE));
                            String unit = mUtil.null2string(itemSubList.get(row1)
                                    .get(Constants.KEY_UNIT));
                            String cmdclsValueMsg = mUtil.null2string(itemSubList.get(row1)
                                    .get(Constants.KEY_CMDCLS_VALUE_MSG));
                            String imageFileName = mUtil.null2string(itemSubList.get(row1)
                                    .get(Constants.KEY_IMAGE_FILE_NAME));

                            mUtil.getTextView(childView, R.id.tvRowState).setText((cmdclsValueMsg.equals("")
                                    ? cmdclsValue : cmdclsValueMsg) + unit + (
                                    conditionTypeCode.equals("01")
                                            ? ""
                                            : conditionTypeCodeName));

                            mUtil.setImage(mActivity, imageFileName, mUtil.getImageView(childView, R.id.ivRowIcon));
                            mUtil.getLinearLayout(mActivity, R.id.llActionBody).addView(childView);
                        }
                    } else if (itemSubTypeCode.equals("03")) {
                        mUtil.getLinearLayout(mActivity, R.id.llAlarm).setVisibility(View.VISIBLE);
                        //                        for ( int row1 = 0; row1 < itemSubList.size(); row1++ ) {
                        int row1 = 0;
                        LinearLayout childView = (LinearLayout) View.inflate(
                                this, R.layout.row_rules_actions_alram_list, null);

                        String cmdclsValue = mUtil.null2string(itemSubList.get(row1)
                                .get(Constants.KEY_CMDCLS_VALUE));
                        mAlarmMsg.setText(cmdclsValue);
//                        mUtil.getTextView(childView, R.id.tvRowTitle).setText(cmdclsValue);
//                        mUtil.getLinearLayout(mActivity, R.id.llAlramBody).addView(childView);
                        //                        }
                    }
                }
            }
        } else {
            mUtil.getLinearLayout(mActivity, R.id.llAction).setVisibility(View.GONE);
        }
    }

    /**
     * Conditions data initialize.
     */
    void setDispConditionsInit() {

        Dlog.v("actions=", actions);
        conditionList.clear();
        conditionList = mUtil.jsonToArrayListMap(conditions);
        getAlListConditions(0);
    }

    /**
     * Get conditions data.
     *
     * @param type Conditions type
     * @return Conditions data string
     */
    private String getAlListConditions(int type) {
        //        type   = 1: 요일 담아주기
        String retValue = "";
        if (type == 1) {
            if (conditionList.size() > 0) {
                for (int row = 0; row < conditionList.size(); row++) {
                    HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                    hmTemp = conditionList.get(row);

                    String itemSubTypeCode = mUtil.null2string(hmTemp.get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                    if (itemSubTypeCode.equals("22")) {
                        //요일
                        ArrayList<HashMap<String, Object>> itemSubList = new ArrayList<>();
                        if (!mUtil.null2string(hmTemp.get(Constants.KEY_ITEM_SUB)).equals("")) {
                            itemSubList = (ArrayList<HashMap<String, Object>>) hmTemp
                                    .get(Constants.KEY_ITEM_SUB);
                            if (itemSubList.size() > 0) {
                                HashMap<String, Object> itemSubMap = new HashMap<String, Object>();
                                itemSubMap = itemSubList.get(0);

                                String cmdclsValueMsg = mUtil.null2string(itemSubMap
                                        .get(Constants.KEY_CMDCLS_VALUE_MSG));
                                retValue = cmdclsValueMsg;
                            }
                        }
                        break;
                    }
                }
            }
        } else {
            mUtil.getLinearLayout(mActivity, R.id.llCondition).setVisibility(View.GONE);
            mUtil.getLinearLayout(mActivity, R.id.llConditionBody1Title).setVisibility(View.GONE);
            mUtil.getLinearLayout(mActivity, R.id.llConditionBody2Title).setVisibility(View.GONE);
            mUtil.getLinearLayout(mActivity, R.id.llConditionBody3Title).setVisibility(View.GONE);
            mUtil.getLinearLayout(mActivity, R.id.llConditionBody1).setVisibility(View.GONE);
            mUtil.getLinearLayout(mActivity, R.id.llConditionBody2).setVisibility(View.GONE);
            mUtil.getLinearLayout(mActivity, R.id.llConditionBody3).setVisibility(View.GONE);
            mUtil.getLinearLayout(mActivity, R.id.llConditionBody1).removeAllViews();
            mUtil.getLinearLayout(mActivity, R.id.llConditionBody2).removeAllViews();
            mUtil.getLinearLayout(mActivity, R.id.llConditionBody3).removeAllViews();


            if (conditionList.size() > 0) {
                for (int row = 0; row < conditionList.size(); row++) {
                    HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                    hmTemp = conditionList.get(row);

                    String itemSubTypeCode = mUtil.null2string(hmTemp.get(Constants.KEY_ITEM_SUB_TYPE_CODE));

                    if (!itemSubTypeCode.equals("22")) {
                        ArrayList<HashMap<String, Object>> itemSubList = new ArrayList<>();
                        if (!mUtil.null2string(hmTemp.get(Constants.KEY_ITEM_SUB)).equals("")) {
                            itemSubList = (ArrayList<HashMap<String, Object>>) hmTemp
                                    .get(Constants.KEY_ITEM_SUB);
                            if (itemSubList.size() > 0) {
                                mUtil.getView(mActivity, R.id.llCondition).setVisibility(View.VISIBLE);
                                for (int row1 = 0; row1 < itemSubList.size(); row1++) {

                                    LinearLayout childView = (LinearLayout) View.inflate(
                                            this, R.layout.row_rules_conditions_list, null);
                                    mUtil.getView(childView, R.id.btnRowDelete).setVisibility(View.GONE);
                                    mUtil.getView(childView, R.id.llRowBody_Body).setVisibility(View.GONE);
                                    mUtil.getView(childView, R.id.tvRowState).setVisibility(View.VISIBLE);

                                    if (itemSubTypeCode.equals("02")) {
                                        //모드
                                        mUtil.getLinearLayout(mActivity, R.id.llConditionBody1Title)
                                                .setVisibility(View.VISIBLE);
                                        mUtil.getLinearLayout(mActivity, R.id.llConditionBody1).setVisibility(View.VISIBLE);
                                        String cmdclsValueMsg = mUtil.null2string(itemSubList.get(row1)
                                                .get(Constants.KEY_CMDCLS_VALUE_MSG));

                                        mUtil.getTextView(childView, R.id.tvRowState).setText(cmdclsValueMsg);
                                        mUtil.setImage(R.drawable.img_rule_icon_homemode,
                                                mUtil.getImageView(childView, R.id.ivRowIcon));
                                        mUtil.getLinearLayout(mActivity, R.id.llConditionBody1).addView(childView);
                                    } else if (itemSubTypeCode.equals("21")) {
                                        //기간
                                        mUtil.getLinearLayout(mActivity, R.id.llConditionBody2Title)
                                                .setVisibility(View.VISIBLE);
                                        mUtil.getLinearLayout(mActivity, R.id.llConditionBody2).setVisibility(View.VISIBLE);
                                        String cmdclsValue = mUtil.null2string(itemSubList.get(row1)
                                                .get(Constants.KEY_CMDCLS_VALUE));

                                        mUtil.getTextView(childView, R.id.tvRowState).setText(cmdclsValue);

                                        mUtil.setImage(R.drawable.img_rule_icon_calendar,
                                                mUtil.getImageView(childView, R.id.ivRowIcon));
                                        mUtil.getLinearLayout(mActivity, R.id.llConditionBody2).addView(childView);
                                    } else if (itemSubTypeCode.equals("01")) {
                                        //장치
                                        mUtil.getLinearLayout(mActivity, R.id.llConditionBody3Title)
                                                .setVisibility(View.VISIBLE);
                                        mUtil.getLinearLayout(mActivity, R.id.llConditionBody3).setVisibility(View.VISIBLE);
                                        mUtil.getView(childView, R.id.llRowBody_Body).setVisibility(View.VISIBLE);

                                        String sourceName = mUtil.null2string(itemSubList.get(row1)
                                                .get(Constants.KEY_SOURCE_NAME));
                                        String sourceSubName = mUtil.null2string(itemSubList.get(row1)
                                                .get(Constants.KEY_SOURCE_SUB_NAME));
                                        String deleteYn = mUtil.null2string(itemSubList.get(row1)
                                                .get(Constants.KEY_DELETE_YN));

                                        if (deleteYn.equals("Y")) {
                                            mUtil.getTextView(childView, R.id.tvRowTitle)
                                                    .setText(mUtil.setSpCenterLine(mActivity, sourceName));
                                        } else {
                                            mUtil.getTextView(childView, R.id.tvRowTitle).setText(sourceName);
                                        }
                                        mUtil.getTextView(childView, R.id.tvRowBody).setText(sourceSubName);
                                        mUtil.getTextView(childView, R.id.tvRowState).setVisibility(View.VISIBLE);
                                        String conditionTypeCode = mUtil.null2string(itemSubList.get(row1)
                                                .get(Constants.KEY_CONDITION_TYPE_CODE));
                                        String conditionTypeCodeName = mUtil.null2string(itemSubList.get(row1)
                                                .get(Constants.KEY_CONDITION_TYPE_CODE_NAME));
                                        String cmdclsValue = mUtil.null2string(itemSubList.get(row1)
                                                .get(Constants.KEY_CMDCLS_VALUE));
                                        String cmdclsValueMsg = mUtil.null2string(itemSubList.get(row1)
                                                .get(Constants.KEY_CMDCLS_VALUE_MSG));
                                        String imageFileName = mUtil.null2string(itemSubList.get(row1)
                                                .get(Constants.KEY_IMAGE_FILE_NAME));
                                        String unit = mUtil.null2string(itemSubList.get(row1)
                                                .get(Constants.KEY_UNIT));

                                        mUtil.getTextView(childView, R.id.tvRowState).setText((cmdclsValueMsg.equals("")
                                                ? cmdclsValue : cmdclsValueMsg)
                                                + unit
                                                + (conditionTypeCode.equals("01") ? "" : conditionTypeCodeName));

                                        mUtil.setImage(mActivity, imageFileName, mUtil.getImageView(childView, R.id.ivRowIcon));
                                        mUtil.getLinearLayout(mActivity, R.id.llConditionBody3).addView(childView);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return retValue;
    }

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            type = msg.what;
            switch (msg.what) {
                case MSG_COM_G_RULES_HOMEGRP_RULE_ID:
                    sendGetRuleDetail();
                    break;
                case MSG_COM_D_RULES_HOMEGRP_RULE_ID:
                    sendDeleteRule();
                    break;
                case MSG_COM_P_RULES_HOMEGRP_RULE_ID_STATUS:
                    sendPutRuleStatus();
                    break;
                default:
                    break;
            }
            return true;
        }
    }
}
