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

package com.ntels.onecable.view.rules;

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.CustomActionBarActivity;
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.LinearLayout;
import android.widget.Toast;

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

/**
 * <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 CustomActionBarActivity 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 homegrpRuleId = "";
    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 act;
    private AppConfig appConfig;
    private Intent intent;
    private Util util = new Util();
    private CustomDialog customDialog = new CustomDialog();

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        act = RulesDetail.this;
        appConfig = (AppConfig) act.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);

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

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

        setToolbar();
        setDisp();
    }

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

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

        util.getTextView(toolbar, R.id.tvToolbarTitle1)
                .setText(util.getString(act, R.string.layout_rules_detail_01));

        util.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(util.getPopMenu(6));

                if (appConfig.getSelect_Homegrp_Grade_Code().equals("MAS")) {
                    alMenuList.add(util.getPopMenu(19));
                    alMenuList.add(util.getPopMenu(18));
                }
                msgAlertList(alMenuList);
            }
        });
    }

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

        util.getView(act, R.id.btnOnOff).setOnClickListener(this);
        util.getView(act, R.id.llBtn1).setOnClickListener(this);

        swipeRefreshLayout = (SwipeRefreshLayout) act.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), 10);
                }
            }
        });
        if (appConfig.getSelect_Homegrp_Grade_Code().equals("MAS")) {
            util.getView(act, R.id.llState).setVisibility(View.VISIBLE);
        } else {
            util.getView(act, R.id.llState).setVisibility(View.GONE);
        }
        comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_RULES_HOMEGRP_RULE_ID), 10);
    }

    @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")) {
                    util.setShowToast(act, util.getString(act, R.string.MSG808), Toast.LENGTH_SHORT);
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(
                            MSG_COM_P_RULES_HOMEGRP_RULE_ID_STATUS), 10);
                } else if (ruleUseYn.equals("N")) {
                    util.setShowToast(act, util.getString(act, R.string.MSG809), Toast.LENGTH_SHORT);
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(
                            MSG_COM_P_RULES_HOMEGRP_RULE_ID_STATUS), 10);
                } else if (ruleUseYn.equals("X")) {
                    customDialog.msgAlert(act, Constants.MSG818, R.string.MSG_TITLE_000,
                            util.getString(act, R.string.MSG_BTN_EDIT),
                            util.getString(act, R.string.MSG_BTN_CANCEL));
                }
                break;
            default:
                break;
        }
    }

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

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

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

            if (ruleUseYn.equals("Y")) {
                util.getButton(act, R.id.btnOnOff).setSelected(true);
                util.getView(act, R.id.tvNotice).setVisibility(View.GONE);
            } else if (ruleUseYn.equals("N")) {
                util.getView(act, R.id.tvNotice).setVisibility(View.GONE);
            }
            String statusCode = "";

            if (ruleUseYn.equals("Y")) {
                statusCode = "03";
            } else if (ruleUseYn.equals("N")) {
                statusCode = "02";
            }
            httpSend.P_rules_homegrp_rule_id_status(homegrpRuleId, 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), 10);
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
                String errorCode = util.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String errorMsg = util.null2string(joResult.get(Constants.KEY_ERR_MSG));

                if (errorCode.equals("401")) {
                    customDialog.msgAlert(act, Constants.MSG998, errorMsg);
                } else {
                    customDialog.msgAlert(act, Constants.MSG000, errorMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(act, Constants.MSG807);
        }
    }

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

        try {
            HttpSend httpSend;

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

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

                    resultGetRuleDetail(result);
                }
            });
            httpSend.G_rules_homegrp_rule_id(homegrpRuleId);
        } 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 = util.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String errorMsg = util.null2string(joResult.get(Constants.KEY_ERR_MSG));

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

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

        try {
            HttpSend httpSend;

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

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

                    resultDeleteRule(result);
                }
            });
            httpSend.D_rules_homegrp_rule_id(homegrpRuleId);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

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

        try {
            if (result.getStatusCode() == 200) {
                isReload = true;
                util.setShowToast(act, util.getString(act, R.string.MSG857), Toast.LENGTH_SHORT);
                intent = new Intent();
                intent.putExtra(Constants.EXTRA_RELOAD_FLAG, isReload);
                act.setResult(RESULT_OK, intent);
                finish();
            } else {
                JSONObject joResult = new JSONObject(result.getContent());
                Dlog.v(joResult.toString());
                String errorCode = util.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String errorMsg = util.null2string(joResult.get(Constants.KEY_ERR_MSG));

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

    @Override
    public void onBackPressed() {

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

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

        try {
            DialogCustomList.Builder dialogListBuilder = new DialogCustomList.Builder(act);
            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), 10);
                            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(act, Constants.MSG810, R.string.MSG_TITLE_003,
                                    util.getString(act, R.string.layout_delete),
                                    util.getString(act, R.string.layout_cancel));
                            break;
                        case 19:
                            Intent intent = new Intent(act, RulesEdit.class);
                            intent.putExtra(Constants.EXTRA_CALL_TYPE, "2");
                            intent.putExtra(Constants.EXTRA_MEMBER_RULE_ID, homegrpRuleId);
                            util.callActivityForResult(act, 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:
                util.callApp_Start(act, "LOGOUT");
                break;
            case Constants.MSG997:
                util.callApp_Start(act, "HOME_RELOAD");
                break;
            case Constants.MSG807:
                if (btnResult == 1) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(type), 10);
                }
                break;
            case Constants.MSG810:
                if (btnResult == 1) {
                    comHandler.sendMessageDelayed(comHandler.obtainMessage(
                            MSG_COM_D_RULES_HOMEGRP_RULE_ID), 10);
                }
                break;
            case Constants.MSG818:
                if (btnResult == 1) {
                    Intent intent = new Intent(act, RulesEdit.class);
                    intent.putExtra(Constants.EXTRA_CALL_TYPE, "2");
                    intent.putExtra(Constants.EXTRA_MEMBER_RULE_ID, homegrpRuleId);
                    util.callActivityForResult(act, 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 == act.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), 10);
                    }
                    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), 10);
                    }
                    break;
                default:
                    break;
            }
        }
    }

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

        try {
            JSONObject joResult = new JSONObject(content);

            homegrpRuleId = util.null2string(joResult.get(Constants.KEY_HOMEGRP_RULE_ID));
            String ruleName = util.null2string(joResult.get(Constants.KEY_RULE_NAME));
            util.getTextView(act, R.id.tvRulesName).setText(ruleName);

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

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

            util.getButton(act, R.id.btnOnOff).setSelected(false);
            if (ruleUseYn.equals("Y")) {
                util.getButton(act, R.id.btnOnOff).setSelected(true);
                util.getView(act, R.id.tvNotice).setVisibility(View.GONE);
            } else if (ruleUseYn.equals("N")) {
                util.getView(act, R.id.tvNotice).setVisibility(View.GONE);
            } else if (ruleUseYn.equals("X")) {
                util.getView(act, R.id.tvNotice).setVisibility(View.VISIBLE);
            }

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

            setDispConditions_init();
            setDispTriggersInit();
            setDispActions_init();
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(act, Constants.MSG807);
        }
    }

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

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

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

        Dlog.v("alList_Triggers1 = ", triggerList.toString());
        if (triggerList.size() > 0) {
            util.getLinearLayout(act, R.id.llTrigger).setVisibility(View.VISIBLE);
            util.getLinearLayout(act, 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);
            util.getView(childView, R.id.btnRowDelete).setVisibility(View.GONE);

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

            ArrayList<HashMap<String, Object>> itemSubList = new ArrayList<HashMap<String, Object>>();
            if (!util.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 = util.getString(act, R.string.layout_rules_triggers_select_02);
                    String httpHour = util.null2string(itemSubList.get(row1).get(Constants.KEY_HOUR));
                    String minute = util.null2string(itemSubList.get(row1).get(Constants.KEY_MINUTE));
                    String[] time = util.UTCtoLocal6(httpHour + minute);
                    String ampm = (util.str2int(time[0]) >= 12
                            ? util.getString(act, R.string.layout_pm) : util.getString(act, R.string.layout_am));
                    String hour = (util.str2int(time[0]) >= 12
                            ? decimalFormat.format((util.str2int(time[0]) - 12)) : time[0]);
                    String dayOfWeek = getAlList_Conditions(1);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            util.getLinearLayout(act, R.id.llAction).setVisibility(View.GONE);
            util.getLinearLayout(act, R.id.llActionBody).removeAllViews();

            util.getLinearLayout(act, R.id.llAlram).setVisibility(View.GONE);
            util.getLinearLayout(act, 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 = util.null2string(hmTemp.get(Constants.KEY_ITEM_SUB_TYPE_CODE));

                ArrayList<HashMap<String, Object>> itemSubList = new ArrayList<HashMap<String, Object>>();
                if (!util.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")) {
                        util.getLinearLayout(act, 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);
                            util.getView(childView, R.id.btnRowDelete).setVisibility(View.GONE);

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

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

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

                            util.setImage(act, imageFileName, util.getImageView(childView, R.id.ivRowIcon));
                            util.getLinearLayout(act, R.id.llActionBody).addView(childView);
                        }
                    } else if (itemSubTypeCode.equals("03")) {
                        util.getLinearLayout(act, R.id.llAlram).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 = util.null2string(itemSubList.get(row1)
                                .get(Constants.KEY_CMDCLS_VALUE));
                        util.getTextView(childView, R.id.tvRowTitle).setText(cmdclsValue);
                        util.getLinearLayout(act, R.id.llAlramBody).addView(childView);
                        //                        }
                    }
                }
            }
        } else {
            util.getLinearLayout(act, R.id.llAction).setVisibility(View.GONE);
        }
    }

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

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

    /**
     * Get conditions data.
     *
     * @param type Conditions type
     *
     * @return Conditions data string
     */
    private String getAlList_Conditions(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 = util.null2string(hmTemp.get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                    if (itemSubTypeCode.equals("22")) {
                        //요일
                        ArrayList<HashMap<String, Object>> itemSubList = new ArrayList<>();
                        if (!util.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 = util.null2string(itemSubMap
                                        .get(Constants.KEY_CMDCLS_VALUE_MSG));
                                retValue = cmdclsValueMsg;
                            }
                        }
                        break;
                    }
                }
            }
        } else {
            util.getLinearLayout(act, R.id.llCondition).setVisibility(View.GONE);
            util.getLinearLayout(act, R.id.llConditionBody1Title).setVisibility(View.GONE);
            util.getLinearLayout(act, R.id.llConditionBody2Title).setVisibility(View.GONE);
            util.getLinearLayout(act, R.id.llConditionBody3Title).setVisibility(View.GONE);
            util.getLinearLayout(act, R.id.llConditionBody1).setVisibility(View.GONE);
            util.getLinearLayout(act, R.id.llConditionBody2).setVisibility(View.GONE);
            util.getLinearLayout(act, R.id.llConditionBody3).setVisibility(View.GONE);
            util.getLinearLayout(act, R.id.llConditionBody1).removeAllViews();
            util.getLinearLayout(act, R.id.llConditionBody2).removeAllViews();
            util.getLinearLayout(act, 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 = util.null2string(hmTemp.get(Constants.KEY_ITEM_SUB_TYPE_CODE));

                    if (!itemSubTypeCode.equals("22")) {
                        ArrayList<HashMap<String, Object>> itemSubList = new ArrayList<>();
                        if (!util.null2string(hmTemp.get(Constants.KEY_ITEM_SUB)).equals("")) {
                            itemSubList = (ArrayList<HashMap<String, Object>>) hmTemp
                                    .get(Constants.KEY_ITEM_SUB);
                            if (itemSubList.size() > 0) {
                                util.getView(act, 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);
                                    util.getView(childView, R.id.btnRowDelete).setVisibility(View.GONE);
                                    util.getView(childView, R.id.llRowBody_Body).setVisibility(View.GONE);
                                    util.getView(childView, R.id.tvRowState).setVisibility(View.VISIBLE);

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

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

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

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

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

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

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

                                        util.setImage(act, imageFileName, util.getImageView(childView, R.id.ivRowIcon));
                                        util.getLinearLayout(act, 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;
        }
    }
}
