/*
 * 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.LogUtil;
import com.ntels.onecable.common.util.Util;
import com.ntels.onecable.common.widget.CustomActivity;
import com.ntels.onecable.common.widget.CustomScrollView;
import com.ntels.onecable.view.dialog.CustomDialog;
import com.ntels.onecable.view.dialog.DialogSpinner;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

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

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

    private static final int MSG_COM_G_RULES_HOMEGRP_RULE_ID = 1;
    private static final int MSG_COM_G_MODES = 2;
    private static final int MSG_COM_P_RULES = 3;
    private static final int MSG_COM_P_RULES_HOMEGRP_RULE_ID = 4;
    Handler mComHandler = new Handler(new IncomingHandlerCallBack());
    private DecimalFormat mDecimalFormat = new DecimalFormat("00");
    private String mHomegrpRuleId = "";
    private String mRuleUseYn = "N";
    private String mRuleName = "";
    private ArrayList<HashMap<String, Object>> mConditionList = new ArrayList<>();
    private ArrayList<HashMap<String, Object>> mActionList = new ArrayList<>();
    private ArrayList<HashMap<String, Object>> mTriggerList = new ArrayList<>();
    private String mTriggers;
    private String mActions;
    private String mConditions;
    private String mCustomJson = "";
    private ArrayList<String> mModeIds = new ArrayList<>();
    private ArrayList<String> mModeTitles = new ArrayList<>();
    private ArrayList<String> mModeResults = new ArrayList<>();
    private String mMode = "";
    private String mModeCode = "";
    private int mModePosition = -1;
    private int mModeType = 2;
    /*통신 관련*/
    private int mType = 0;
    /*공통*/
    private Activity mActivity;
    private AppConfig mAppConfig;
    private Intent mIntent;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private String mCallType = "";

    @BindView(R.id.edtRulesName) EditText mRulesName;
    @BindView(R.id.ivRulesNameAdd) ImageView mRulesNameAdd;
    @BindView(R.id.btnRulesNameOk) Button mRulesNameOk;
    @BindView(R.id.edtAlarmMsg) EditText mAlarmMsg;
    @BindView(R.id.ivAlarmMsgAdd) ImageView mAlarmMsgAdd;
    @BindView(R.id.btnAlarmMsgOk) Button mAlarmMsgOk;
    @BindView(R.id.svBody) CustomScrollView mCustomScrollView;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        mActivity = RulesEdit.this;
        mAppConfig = (AppConfig) mActivity.getApplicationContext();
        mCustomDialog.setOnMsgAlterToResultEvent(this);

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

        ButterKnife.bind(this);

        if (null != getIntent()) {
            Intent intent = getIntent();
            //EXTRA_CALL_TYPE = 1:규칙 만들기 2:규칙수정
            mCallType = intent.getStringExtra(Constants.EXTRA_CALL_TYPE);
            mHomegrpRuleId = 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.GONE);

        if (mCallType.equals("1")) {
            mUtil.getTextView(toolbar, R.id.tvToolbarTitle1)
                    .setText(mUtil.getString(mActivity, R.string.layout_rules_edit_01));
        } else if (mCallType.equals("2")) {
            mUtil.getTextView(toolbar, R.id.tvToolbarTitle1)
                    .setText(mUtil.getString(mActivity, R.string.layout_rules_edit_02));
        }
    }

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

//        mUtil.getView(mActivity, R.id.llTriggerTitle).setOnClickListener(this);
//        mUtil.getView(mActivity, R.id.llActionTitle).setOnClickListener(this);
//        mUtil.getView(mActivity, R.id.llConditionTitle).setOnClickListener(this);
//        mUtil.getView(mActivity, R.id.llConditionBody1Title).setOnClickListener(this);
//        mUtil.getView(mActivity, R.id.llConditionBody2Title).setOnClickListener(this);
//        mUtil.getView(mActivity, R.id.llConditionBody3Title).setOnClickListener(this);

//        mUtil.getView(mActivity, R.id.llBtn1).setOnClickListener(this);
//        mUtil.getView(mActivity, R.id.llBtn2).setOnClickListener(this);

        mUtil.setKeyboardHide(mActivity, mUtil.getLinearLayout(mActivity, R.id.llPageRoot));
        mUtil.setKeyboardHide(mActivity, mUtil.getLinearLayout(mActivity, R.id.llSvbody));

        if (mCallType.equals("2")) {
            mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_RULES_HOMEGRP_RULE_ID), Constants.HANDLER_DELAY_MILLIS);
        }

        mRulesName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                if (before > 0 || count > 0) {
                    mRulesNameOk.setVisibility(View.VISIBLE);
                    mRulesNameAdd.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        // 스크롤뷰 안에서 알람메시지가 개별 스크롤 가능하도록 처리
        /*mAlarmMsg.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mCustomScrollView.requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });*/
        // 알람메시지 라인 수 4줄로 제한
        mAlarmMsg.addTextChangedListener(new TextWatcher() {
            String prevString = "";
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                prevString = charSequence.toString();
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                if ((before > 0 || count > 0) && !prevString.equals(charSequence.toString())) {
                    mAlarmMsgOk.setVisibility(View.VISIBLE);
                    mAlarmMsgAdd.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (mAlarmMsg.getLineCount() >= 5) {
                    mAlarmMsg.setText(prevString);
                    mAlarmMsg.setSelection(mAlarmMsg.length());
                }
            }
        });
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);
    }

    @SuppressWarnings("unchecked")
    @OnClick({R.id.llTriggerTitle, R.id.llActionTitle, R.id.llConditionTitle, R.id.llBtn1, R.id.llBtn2, R.id.btnRulesNameOk,
            R.id.ivRulesNameAdd, R.id.btnAlarmMsgOk, R.id.ivAlarmMsgAdd})
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.llBtn1:
                if (mUtil.getEditTextVal(mActivity, R.id.edtRulesName).equals("")) {
                    mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG824), Toast.LENGTH_SHORT);
                    return;
                }

                Dlog.v("111111");
                //알람내용이 없으면 삭제한다
                for (int row = 0; row < mActionList.size(); row++) {
                    Dlog.v("222222");
                    String itemSubTypeCode = mUtil.null2string(mActionList.get(row)
                            .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                    if (itemSubTypeCode.equals("03")) {
                        Dlog.v("333333");
                        if (!mUtil.null2string(mActionList.get(row).get(Constants.KEY_ITEM_SUB)).equals("")) {
                            Dlog.v("444444");
                            ArrayList<HashMap<String, Object>> itemSubList =
                                    (ArrayList<HashMap<String, Object>>) mActionList.get(row)
                                            .get(Constants.KEY_ITEM_SUB);
                            for (int row1 = 0; row1 < itemSubList.size(); row1++) {
                                Dlog.v("555555");
                                String cmdclsValue = mUtil.null2string(itemSubList.get(row1)
                                        .get(Constants.KEY_CMDCLS_VALUE));
                                if (cmdclsValue.equals("")) {
                                    itemSubList.remove(row1);
                                    if (itemSubList.size() == 0) {
                                        mActionList.remove(row);
                                    }
                                    break;
                                }
                            }
                            break;
                        }
                    }
                }

                if (mTriggerList.size() == 0) {
                    mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG825), Toast.LENGTH_SHORT);
                    return;
                }

                if (mActionList.size() == 0) {
                    mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG832), Toast.LENGTH_SHORT);
                    return;
                }

                if (mRuleUseYn.equals("X")) {
                    Boolean isCheck = false;
                    if (!isCheck) {
                        if (mTriggerList.size() > 0) {
                            for (int row = 0; row < mTriggerList.size(); row++) {
                                ArrayList<HashMap<String, Object>> tempItemSubList =
                                        (ArrayList<HashMap<String, Object>>) mTriggerList.get(row)
                                                .get(Constants.KEY_ITEM_SUB);

                                for (int row1 = 0; row1 < tempItemSubList.size(); row1++) {
                                    String deleteYn = mUtil.null2string(tempItemSubList.get(row1)
                                            .get(Constants.KEY_DELETE_YN));
                                    if (deleteYn.equals("Y")) {
                                        isCheck = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if (!isCheck) {
                        if (mActionList.size() > 0) {
                            for (int row = 0; row < mActionList.size(); row++) {
                                ArrayList<HashMap<String, Object>> tempItemSubList =
                                        (ArrayList<HashMap<String, Object>>) mActionList.get(row)
                                                .get(Constants.KEY_ITEM_SUB);

                                for (int row1 = 0; row1 < tempItemSubList.size(); row1++) {
                                    String deleteYn = mUtil.null2string(tempItemSubList.get(row1)
                                            .get(Constants.KEY_DELETE_YN));
                                    if (deleteYn.equals("Y")) {
                                        isCheck = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if (!isCheck) {
                        if (mConditionList.size() > 0) {
                            for (int row = 0; row < mConditionList.size(); row++) {
                                ArrayList<HashMap<String, Object>> tempItemSubList =
                                        (ArrayList<HashMap<String, Object>>) mConditionList.get(row)
                                                .get(Constants.KEY_ITEM_SUB);

                                for (int row1 = 0; row1 < tempItemSubList.size(); row1++) {
                                    String deleteYn = mUtil.null2string(tempItemSubList.get(row1)
                                            .get(Constants.KEY_DELETE_YN));
                                    if (deleteYn.equals("Y")) {
                                        isCheck = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    if (isCheck) {
                        mCustomDialog.msgAlert(mActivity, Constants.MSG875);
                        return;
                    }
                }

                if (mCallType.equals("1")) {
                    mComHandler.sendMessage(mComHandler.obtainMessage(MSG_COM_P_RULES));
                } else if (mCallType.equals("2")) {
                    mComHandler.sendMessage(mComHandler.obtainMessage(MSG_COM_P_RULES_HOMEGRP_RULE_ID));
                }
                break;
            case R.id.llBtn2:
                onBackPressed();
                break;
            case R.id.llTriggerTitle:
                if (!view.isSelected()) {
                    Intent intent = new Intent(mActivity, RulesTriggersSelect.class);
                    intent.putExtra(Constants.EXTRA_TRIGGERS, mTriggerList);
                    intent.putExtra(Constants.EXTRA_CONDITIONS, mConditionList);
                    mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_RULES_TRIGGERS_SELECT);
                }
                break;
            case R.id.llActionTitle:
                mUtil.callBtnGoogleAnalytics(mActivity, "Set_Action", "");
                mIntent = new Intent(mActivity, RulesThingsSelect.class);
                mIntent.putExtra(Constants.EXTRA_CALL_TYPE, "2");
                mIntent.putExtra(Constants.EXTRA_TRIGGERS, mTriggerList);
                mIntent.putExtra(Constants.EXTRA_ACTIONS, mActionList);
                mIntent.putExtra(Constants.EXTRA_CONDITIONS, mConditionList);
                mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_RULES_THINGS_SELECT);
                //                }
                break;
           /* case R.id.llAlramTitle:
                if (!view.isSelected()) {
                    mUtil.callBtnGoogleAnalytics(mActivity, "Set_Msg", "");

                    HashMap<String, Object> itemSubMap = new HashMap<>();
                    String sourceId = "";
                    itemSubMap.put(Constants.KEY_SOURCE_ID, sourceId);
                    String sourceName = "";
                    itemSubMap.put(Constants.KEY_SOURCE_NAME, sourceName);
                    String sourceSubId = "";
                    itemSubMap.put(Constants.KEY_SOURCE_SUB_ID, sourceSubId);
                    String sourceSubName = "";
                    itemSubMap.put(Constants.KEY_SOURCE_SUB_NAME, sourceSubName);
                    String conditionsTypeCode = "02";
                    itemSubMap.put(Constants.KEY_CONDITION_TYPE_CODE, conditionsTypeCode);
                    String conditionTypeCodeName = "";
                    itemSubMap.put(Constants.KEY_CONDITION_TYPE_CODE_NAME, conditionTypeCodeName);
                    String cmdclsValue = "";
                    itemSubMap.put(Constants.KEY_CMDCLS_VALUE, cmdclsValue);
                    String cmdclsValueMsg = "";
                    itemSubMap.put(Constants.KEY_CMDCLS_VALUE_MSG, cmdclsValueMsg);
                    String unit = "";
                    itemSubMap.put(Constants.KEY_UNIT, unit);
                    String dataTypeCode = "";
                    itemSubMap.put(Constants.KEY_DATA_TYPE_CODE, dataTypeCode);
                    String dayOfWeek = "";
                    itemSubMap.put(Constants.KEY_DAYOFWEEK, dayOfWeek);
                    String repeatable = "";
                    itemSubMap.put(Constants.KEY_REPEATABLE, repeatable);
                    String hour = "";
                    itemSubMap.put(Constants.KEY_HOUR, hour);
                    String minute = "";
                    itemSubMap.put(Constants.KEY_MINUTE, minute);
                    String imageFileName = "";
                    itemSubMap.put(Constants.KEY_IMAGE_FILE_NAME, imageFileName);
                    String deleteYn = "";
                    itemSubMap.put(Constants.KEY_DELETE_YN, deleteYn);
                    itemSubMap.put(Constants.KEY_ACTION_TYPE_CODE, "00");

                    ArrayList<HashMap<String, Object>> tempItemSubList = new ArrayList<>();
                    HashMap<String, Object> hmTempActions = new HashMap<>();
                    //액션이 아예 없는 경우
                    tempItemSubList.add(itemSubMap);
                    hmTempActions.put(Constants.KEY_ITEM_NAME,
                            mUtil.getString(mActivity, R.string.layout_rules_detail_04));
                    hmTempActions.put(Constants.KEY_ITEM_SUB_TYPE_CODE, "03");
                    hmTempActions.put(Constants.KEY_ITEM_SUB, tempItemSubList);
                    mActionList.add(hmTempActions);

                    setDispActions();
                }
                break;*/
            case R.id.llConditionTitle:
                mIntent = new Intent(mActivity, RulesConditionSelect.class);
                mIntent.putExtra(Constants.EXTRA_TRIGGERS, mTriggerList);
                mIntent.putExtra(Constants.EXTRA_ACTIONS, mActionList);
                mIntent.putExtra(Constants.EXTRA_CONDITIONS, mConditionList);
                mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_RULES_CONDITION_SELECT);
                /*if (!view.isSelected()) {
                    view.setSelected(true);
                    mUtil.getView(mActivity, R.id.llConditionBody).setVisibility(View.VISIBLE);
                } else {
                    view.setSelected(false);
                    mUtil.getView(mActivity, R.id.llConditionBody).setVisibility(View.GONE);
                }*/
                break;
            case R.id.llConditionBody1Title:
                if (!view.isSelected()) {
                    mUtil.callBtnGoogleAnalytics(mActivity, "Set_Condition", "Condi_Homemode");
                    mMode = "";
                    mModeCode = "";
                    mModePosition = -1;
                    mModeResults.clear();
                    callModeSpinner();
                }
                break;
            case R.id.llConditionBody2Title:
                if (!view.isSelected()) {
                    mUtil.callBtnGoogleAnalytics(mActivity, "Set_Condition", "Condi_Period");
                    mIntent = new Intent(mActivity, RulesDateSelect.class);
                    mIntent.putExtra(Constants.EXTRA_DATE, "");
                    mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_RULES_DATE_SELECT);
                }
                break;
            case R.id.llConditionBody3Title:
                mUtil.callBtnGoogleAnalytics(mActivity, "Set_Condition", "Condi_Things");
                mIntent = new Intent(mActivity, RulesThingsSelect.class);
                mIntent.putExtra(Constants.EXTRA_CALL_TYPE, "3");
                mIntent.putExtra(Constants.EXTRA_TRIGGERS, mTriggerList);
                mIntent.putExtra(Constants.EXTRA_ACTIONS, mActionList);
                mIntent.putExtra(Constants.EXTRA_CONDITIONS, mConditionList);
                mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_RULES_THINGS_SELECT);
                break;
            case R.id.ivRulesNameAdd:
                if (mRulesName.length() > 0) {
                    // 삭제 버튼을 눌렀을 때
                    mRulesName.setText("");
//                    mRulesNameAdd.setBackgroundResource(R.drawable.d_common_list_btn_add);
                    mRulesNameAdd.setVisibility(View.INVISIBLE);
                    mRulesNameOk.setVisibility(View.GONE);
                    mRulesName.clearFocus();
                } else {
//                    mRulesName.requestFocus();
//                    displayKeyboard(mRulesName, true);
                }
                break;
            case R.id.btnRulesNameOk:
                mRulesName.clearFocus();
                mRulesNameOk.setVisibility(View.GONE);
//                mRulesNameAdd.setVisibility(View.VISIBLE);
                if (mRulesName.length() > 0) {
                    mRulesNameAdd.setVisibility(View.VISIBLE);
                } else {
                    mRulesNameAdd.setVisibility(View.INVISIBLE);
                }
                displayKeyboard(mRulesName, false);
                break;
            case R.id.ivAlarmMsgAdd:
                if (mAlarmMsg.length() > 0) {
                    // 삭제 버튼을 눌렀을 때
                    mAlarmMsg.setText("");
//                    mAlarmMsgAdd.setBackgroundResource(R.drawable.d_common_list_btn_add);
                    mAlarmMsgAdd.setVisibility(View.INVISIBLE);
                    mAlarmMsgOk.setVisibility(View.GONE);
                    mRulesName.clearFocus();

                    int tag = (int) mAlarmMsg.getTag();
                    for (int row = 0; row < mActionList.size(); row++) {
                        String itemSubTypeCode = mUtil.null2string(mActionList.get(row).get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                        ArrayList<HashMap<String, Object>> itemSubList;
                        if (!mUtil.null2string(mActionList.get(row).get(Constants.KEY_ITEM_SUB)).equals("")) {
                            itemSubList = (ArrayList<HashMap<String, Object>>) mActionList.get(row).get(Constants.KEY_ITEM_SUB);
                            if (itemSubTypeCode.equals("03")) {
                                itemSubList.remove(tag);
                                mAlarmMsg.setTag(null);
                                if (itemSubList.size() == 0) {
                                    mActionList.remove(row);
                                }
//                                                    mUtil.getView(mActivity, R.id.llAlramTitle).setSelected(false);
                                break;
                            }
                        }
                    }
                } else {
//                    mAlarmMsg.requestFocus();
//                    displayKeyboard(mAlarmMsg, true);
                }
                break;
            case R.id.btnAlarmMsgOk:
                mAlarmMsg.clearFocus();
                mAlarmMsgOk.setVisibility(View.GONE);
//                mAlarmMsgAdd.setVisibility(View.VISIBLE);
                if (mAlarmMsg.length() > 0) {
                    mAlarmMsgAdd.setVisibility(View.VISIBLE);
                } else {
                    mAlarmMsgAdd.setVisibility(View.INVISIBLE);
                }
                displayKeyboard(mAlarmMsg, false);
                if (null != mAlarmMsg.getTag()) {

                    int tag = (int) mAlarmMsg.getTag();

                    for (int row = 0; row < mActionList.size(); row++) {
                        String itemSubTypeCode = mUtil.null2string(mActionList.get(row)
                                .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                        if (!mUtil.null2string(mActionList.get(row)
                                .get(Constants.KEY_ITEM_SUB)).equals("")) {
                            ArrayList<HashMap<String, Object>> itemSubList =
                                    (ArrayList<HashMap<String, Object>>) mActionList.get(row)
                                            .get(Constants.KEY_ITEM_SUB);
                            if (itemSubTypeCode.equals("03")) {
                                itemSubList.get(tag).put(Constants.KEY_CMDCLS_VALUE, mAlarmMsg.getText().toString());
                                break;
                            }
                        }
                    }
                } else {
                    setNewAlarmMsg();
                }
                break;
            default:
                break;
        }
    }

    private void displayKeyboard(View view, boolean isShow) {
        InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (isShow) {
            imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
        } else {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    private void setNewAlarmMsg() {
        mUtil.callBtnGoogleAnalytics(mActivity, "Set_Msg", "");

        HashMap<String, Object> itemSubMap = new HashMap<>();
        String sourceId = "";
        itemSubMap.put(Constants.KEY_SOURCE_ID, sourceId);
        String sourceName = "";
        itemSubMap.put(Constants.KEY_SOURCE_NAME, sourceName);
        String sourceSubId = "";
        itemSubMap.put(Constants.KEY_SOURCE_SUB_ID, sourceSubId);
        String sourceSubName = "";
        itemSubMap.put(Constants.KEY_SOURCE_SUB_NAME, sourceSubName);
        String conditionsTypeCode = "02";
        itemSubMap.put(Constants.KEY_CONDITION_TYPE_CODE, conditionsTypeCode);
        String conditionTypeCodeName = "";
        itemSubMap.put(Constants.KEY_CONDITION_TYPE_CODE_NAME, conditionTypeCodeName);
        String cmdclsValue = mUtil.null2string(mAlarmMsg.getText().toString());
        itemSubMap.put(Constants.KEY_CMDCLS_VALUE, cmdclsValue);
        String cmdclsValueMsg = "";
        itemSubMap.put(Constants.KEY_CMDCLS_VALUE_MSG, cmdclsValueMsg);
        String unit = "";
        itemSubMap.put(Constants.KEY_UNIT, unit);
        String dataTypeCode = "";
        itemSubMap.put(Constants.KEY_DATA_TYPE_CODE, dataTypeCode);
        String dayOfWeek = "";
        itemSubMap.put(Constants.KEY_DAYOFWEEK, dayOfWeek);
        String repeatable = "";
        itemSubMap.put(Constants.KEY_REPEATABLE, repeatable);
        String hour = "";
        itemSubMap.put(Constants.KEY_HOUR, hour);
        String minute = "";
        itemSubMap.put(Constants.KEY_MINUTE, minute);
        String imageFileName = "";
        itemSubMap.put(Constants.KEY_IMAGE_FILE_NAME, imageFileName);
        String deleteYn = "";
        itemSubMap.put(Constants.KEY_DELETE_YN, deleteYn);
        itemSubMap.put(Constants.KEY_ACTION_TYPE_CODE, "00");

        ArrayList<HashMap<String, Object>> tempItemSubList = new ArrayList<>();
        HashMap<String, Object> hmTempActions = new HashMap<>();
        //액션이 아예 없는 경우
        tempItemSubList.add(itemSubMap);
        hmTempActions.put(Constants.KEY_ITEM_NAME, mUtil.getString(mActivity, R.string.layout_rules_detail_05));
        hmTempActions.put(Constants.KEY_ITEM_SUB_TYPE_CODE, "03");
        hmTempActions.put(Constants.KEY_ITEM_SUB, tempItemSubList);
        mActionList.add(hmTempActions);

        setDispActions();
    }

    private void showModeSpinner() {
        mMode = "";
        mModeCode = "";
        mModePosition = -1;
        mModeResults.clear();
        callModeSpinner();
    }

    /**
     * Spinner display.
     */
    void callModeSpinner() {

        if (mModeIds.size() > 0) {
            if (!mModeCode.equals("")) {
                mModeResults.clear();
                String[] strArray = mModeCode.split("\\,", 100);
                for (String s : strArray) {
                    for (int row1 = 0; row1 < mModeIds.size(); row1++) {
                        if (s.equals(mModeIds.get(row1))) {
                            mModeResults.add("" + row1);
                            break;
                        }
                    }
                }
            } else {
                for (int row1 = 0; row1 < mModeIds.size(); row1++) {
                    mModeResults.add("" + row1);
                }
            }

            mIntent = new Intent();
            mIntent.setClass(mActivity, DialogSpinner.class);
            mIntent.putExtra(Constants.EXTRA_SPINNER_LIST1, mModeTitles);
            if (AppConfig.getLanguageType().equalsIgnoreCase(Locale.ENGLISH.toString())) {
                mIntent.putExtra(Constants.EXTRA_SPINNER_TITLE, mUtil.getString(mActivity, R.string.layout_rules_edit_08).substring(4));
            } else {
                mIntent.putExtra(Constants.EXTRA_SPINNER_TITLE, mUtil.getString(mActivity, R.string.layout_rules_edit_08));
            }
            mIntent.putExtra(Constants.EXTRA_SPINNER_TYPE, mModeType);
            if (mModeType == 2) {
                mIntent.putExtra(Constants.EXTRA_SPINNER_POSITION_LIST, mModeResults);
            } else {
                mIntent.putExtra(Constants.EXTRA_SPINNER_POSITION, mModePosition);
            }
            mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_SPINNER);
        } else {
            mComHandler.sendMessage(mComHandler.obtainMessage(MSG_COM_G_MODES));
        }
    }

    /**
     * 홈 규칙 등록(규칙을 등록한다) 요청.
     */
    private void sendPostRules() {
        LogUtil.i(TAG, "mActionList : " + mActionList.toString());

        try {
            HttpSend httpSend;

            httpSend = new HttpSend(mActivity);

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

                    resultPostRules(result);
                }
            });

            mRuleName = mUtil.getEditTextVal(mActivity, R.id.edtRulesName);
            HashMap<String, Object> hmTemp = new HashMap<>();
            hmTemp.put(Constants.KEY_RULE_NAME, mRuleName);
            hmTemp.put(Constants.KEY_USE_YN, "Y");
            hmTemp.put(Constants.KEY_TRIGGERS, mTriggerList);
            hmTemp.put(Constants.KEY_ACTIONS, mActionList);
            hmTemp.put(Constants.KEY_CONDITIONS, mConditionList);

            Dlog.v(mUtil.MapToJson(hmTemp));
            httpSend.P_rules(mUtil.MapToJson(hmTemp));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 홈 규칙 등록(규칙을 등록한다) 요청 결과.
     *
     * @param result 결과 data
     */
    private void resultPostRules(Response result) {

        try {
            if (result.getStatusCode() == 201) {
                /*String itemSubTypeCode = mUtil.null2string(mTriggerList.get(0)
                        .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                mIntent = new Intent(mActivity, RulesAddSucess.class);
                mIntent.putExtra(Constants.EXTRA_CALL_TYPE, itemSubTypeCode);
                mIntent.putExtra(Constants.EXTRA_RULE_NAME, mRuleName);
                mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_RULES_ADD_SUCESS);*/
                Intent intent = new Intent();
                intent.putExtra(Constants.EXTRA_RELOAD_FLAG, true);
                this.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));

                switch (resultCode) {
                    case "401":
                        mCustomDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                        break;
                    case "401-106":
                        mCustomDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                        break;
                    default:
                        mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                        break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    /**
     * 홈 규칙 수정(해당 규칙을 수정한다) 요청.
     */
    private void sendPutRules() {

        try {
            HttpSend httpSend;

            httpSend = new HttpSend(mActivity);

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

                    resultPutRules(result);
                }
            });

            mRuleName = mUtil.getEditTextVal(mActivity, R.id.edtRulesName);
            HashMap<String, Object> hmTemp = new HashMap<>();
            hmTemp.put(Constants.KEY_RULE_NAME, mRuleName);
            hmTemp.put(Constants.KEY_USE_YN, "Y");
            hmTemp.put(Constants.KEY_TRIGGERS, mTriggerList);
            hmTemp.put(Constants.KEY_ACTIONS, mActionList);
            hmTemp.put(Constants.KEY_CONDITIONS, mConditionList);

            Dlog.v(mUtil.MapToJson(hmTemp));

            httpSend.putRuleEdit(mHomegrpRuleId, mUtil.MapToJson(hmTemp));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

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

        try {
            if (result.getStatusCode() == 200) {
                mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG817), Toast.LENGTH_SHORT);
                Intent intent1 = new Intent();
                intent1.putExtra(Constants.EXTRA_RELOAD_FLAG, true);
                this.setResult(RESULT_OK, intent1);
                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));

                switch (resultCode) {
                    case "401":
                        mCustomDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                        break;
                    case "401-106":
                        mCustomDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                        break;
                    default:
                        mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                        break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    /**
     * 홈모드 조회(홈그룹의 홈모드 목록을 불러온다) 요청.
     */
    private void sendGetModes() {

        try {
            HttpSend httpSend;

            httpSend = new HttpSend(mActivity);

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

                    resultGetModes(result);
                }
            });
            httpSend.getModes();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 홈모드 조회(홈그룹의 홈모드 목록을 불러온다) 요청 결과.
     *
     * @param result 결과 data
     */
    private void resultGetModes(Response result) {

        try {
            if (result.getStatusCode() == 200) {
                ArrayList<HashMap<String, Object>> alList = mUtil.jsonToArrayListMap(result.getContent());
                if (alList.size() > 0) {
                    for (int row = 0; row < alList.size(); row++) {
                        HashMap<String, Object> hmTemp;
                        hmTemp = alList.get(row);
                        String modeId = mUtil.null2string(hmTemp.get(Constants.KEY_MODE_ID));
                        String modeName = mUtil.null2string(hmTemp.get(Constants.KEY_MODE_NAME));
                        mModeIds.add(modeId);
                        mModeTitles.add(modeName);
                    }
                }
                callModeSpinner();
            } 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));

                switch (resultCode) {
                    case "401":
                        mCustomDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                        break;
                    case "401-106":
                        mCustomDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                        break;
                    default:
                        mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                        break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

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

        try {
            HttpSend httpSend;

            httpSend = new HttpSend(mActivity);

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

                    resultGetRulesDetail(result);
                }
            });
            httpSend.getRuleDetail(mHomegrpRuleId);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

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

        try {
            if (result.getStatusCode() == 200) {

                setRulesJsonInit(result.getContent());
            } 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));

                switch (resultCode) {
                    case "401":
                        mCustomDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                        break;
                    case "401-106":
                        mCustomDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                        break;
                    default:
                        mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                        break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    @Override
    public void onBackPressed() {

        mIntent = new Intent();
        mActivity.setResult(RESULT_CANCELED, mIntent);
        finish();
    }

    @SuppressWarnings("unchecked")
    @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) {
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(mType), 10);
                }
                break;
            case Constants.MSG875:
                if (btnResult == 1) {

                    if (mTriggerList.size() > 0) {
                        for (int row = 0; row < mTriggerList.size(); row++) {
                            ArrayList<HashMap<String, Object>> tempItemSubList =
                                    (ArrayList<HashMap<String, Object>>) mTriggerList.get(row)
                                            .get(Constants.KEY_ITEM_SUB);

                            for (int row1 = tempItemSubList.size() - 1; row1 >= 0; row1--) {
                                String deleteYn = mUtil.null2string(tempItemSubList.get(row1)
                                        .get(Constants.KEY_DELETE_YN));
                                if (deleteYn.equals("Y")) {
                                    tempItemSubList.remove(row1);
                                    if (tempItemSubList.size() == 0) {
                                        mTriggerList.remove(row);
                                    }
                                }
                            }
                        }
                    }
                    if (mActionList.size() > 0) {
                        for (int row = 0; row < mActionList.size(); row++) {
                            ArrayList<HashMap<String, Object>> tempItemSubList =
                                    (ArrayList<HashMap<String, Object>>) mActionList.get(row)
                                            .get(Constants.KEY_ITEM_SUB);

                            for (int row1 = tempItemSubList.size() - 1; row1 >= 0; row1--) {
                                String deleteYn = mUtil.null2string(tempItemSubList.get(row1)
                                        .get(Constants.KEY_DELETE_YN));
                                if (deleteYn.equals("Y")) {
                                    tempItemSubList.remove(row1);
                                    if (tempItemSubList.size() == 0) {
                                        mActionList.remove(row);
                                    }
                                }
                            }
                        }
                    }
                    if (mConditionList.size() > 0) {
                        for (int row = 0; row < mConditionList.size(); row++) {
                            ArrayList<HashMap<String, Object>> tempItemSubList =
                                    (ArrayList<HashMap<String, Object>>) mConditionList.get(row)
                                            .get(Constants.KEY_ITEM_SUB);

                            for (int row1 = tempItemSubList.size() - 1; row1 >= 0; row1--) {
                                String deleteYn = mUtil.null2string(tempItemSubList.get(row1)
                                        .get(Constants.KEY_DELETE_YN));
                                if (deleteYn.equals("Y")) {
                                    tempItemSubList.remove(row1);
                                    if (tempItemSubList.size() == 0) {
                                        mConditionList.remove(row);
                                    }
                                }
                            }
                        }
                    }
                    mRuleUseYn = "N";

                    setDispTriggers();
                    setDispActions();
                    getAlListConditions(0);
                    mUtil.getView(mActivity, R.id.llBtn1).performClick();
                }
                break;
            default:
                break;
        }
    }

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

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_RULES_ADD_SUCESS:
                    mActivity.setResult(RESULT_OK, data);
                    finish();
                    break;
                case Constants.ACT_RULES_TRIGGERS_SELECT:
                    mTriggerList = (ArrayList<HashMap<String, Object>>) data.getSerializableExtra(
                            Constants.EXTRA_TRIGGERS);
                    mConditionList = (ArrayList<HashMap<String, Object>>) data.getSerializableExtra(
                            Constants.EXTRA_CONDITIONS);

                    setDispTriggers();
                    break;
                case Constants.ACT_RULES_THINGS_SELECT:
                    mActionList = (ArrayList<HashMap<String, Object>>) data.getSerializableExtra(
                            Constants.EXTRA_ACTIONS);
                    mConditionList = (ArrayList<HashMap<String, Object>>) data.getSerializableExtra(
                            Constants.EXTRA_CONDITIONS);

                    setDispActions();
                    getAlListConditions(0);
                    break;
                case Constants.ACT_SPINNER:
                    mMode = "";
                    mModeCode = "";
                    if (mModePosition != data.getIntExtra(Constants.EXTRA_SPINNER_RESULT, -1)) {
                        mModePosition = data.getIntExtra(Constants.EXTRA_SPINNER_RESULT, 0);
                        mMode = mUtil.null2string(mModeTitles.get(mModePosition));
                        mModeCode = mUtil.null2string(mModeIds.get(mModePosition));
                    } else {
                        mModeResults = data.getStringArrayListExtra(Constants.EXTRA_SPINNER_RESULT_LIST);
                        if (mModeResults != null) {
                            if (mModeResults.size() > 0) {
                                for (int row = 0; row < mModeResults.size(); row++) {
                                    if (row > 0) {
                                        mMode += ",";
                                        mModeCode += ",";
                                    }
                                    mMode += mUtil.null2empty(mModeTitles.get(mUtil.str2int(mModeResults.get(row))));
                                    mModeCode += mUtil.null2empty(mModeIds.get(mUtil.str2int(mModeResults.get(row))));
                                }
                            }
                        }
                    }

                    if (!mMode.equals("")) {
                        Dlog.v("mMode", mMode);
                        Dlog.v("mModeCode", mModeCode);

                        HashMap<String, Object> itemSubMap = new HashMap<>();
                        String sourceId = "";
                        itemSubMap.put(Constants.KEY_SOURCE_ID, sourceId);
                        String sourceName = "";
                        itemSubMap.put(Constants.KEY_SOURCE_NAME, sourceName);
                        String sourceSubId = "";
                        itemSubMap.put(Constants.KEY_SOURCE_SUB_ID, sourceSubId);
                        String sourceSubName = "";
                        itemSubMap.put(Constants.KEY_SOURCE_SUB_NAME, sourceSubName);
                        String conditionTypeCode = "";
                        itemSubMap.put(Constants.KEY_CONDITION_TYPE_CODE, conditionTypeCode);
                        String conditionTypeCodeName = "";
                        itemSubMap.put(Constants.KEY_CONDITION_TYPE_CODE_NAME, conditionTypeCodeName);
                        String cmdclsValue = mModeCode;
                        itemSubMap.put(Constants.KEY_CMDCLS_VALUE, cmdclsValue);
                        String cmdclsValueMsg = mMode;
                        itemSubMap.put(Constants.KEY_CMDCLS_VALUE_MSG, cmdclsValueMsg);
                        String unit = "";
                        itemSubMap.put(Constants.KEY_UNIT, unit);
                        String dataTypeCode = "";
                        itemSubMap.put(Constants.KEY_DATA_TYPE_CODE, dataTypeCode);
                        String dayOfWeek = "";
                        itemSubMap.put(Constants.KEY_DAYOFWEEK, dayOfWeek);
                        String repeatable = "";
                        itemSubMap.put(Constants.KEY_REPEATABLE, repeatable);
                        String hour = "";
                        itemSubMap.put(Constants.KEY_HOUR, hour);
                        String minute = "";
                        itemSubMap.put(Constants.KEY_MINUTE, minute);
                        String imageFileName = "";
                        itemSubMap.put(Constants.KEY_IMAGE_FILE_NAME, imageFileName);
                        String deleteYn = "";
                        itemSubMap.put(Constants.KEY_DELETE_YN, deleteYn);

                        ArrayList<HashMap<String, Object>> itemSubList = new ArrayList<>();

                        HashMap<String, Object> hmTempConditions = new HashMap<>();
                        Boolean isCheck = false;
                        if (mConditionList.size() > 0) {
                            for (int row = 0; row < mConditionList.size(); row++) {
                                String itemSubTypeCode = mUtil.null2string(mConditionList.get(row)
                                        .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                                if (itemSubTypeCode.equals("02")) {
                                    itemSubList = (ArrayList<HashMap<String, Object>>) mConditionList.get(row)
                                            .get(Constants.KEY_ITEM_SUB);
                                    itemSubList.clear();
                                    itemSubList.add(itemSubMap);
                                    isCheck = true;
                                    break;
                                }
                            }
                        }
                        if (!isCheck) {
                            itemSubList.add(itemSubMap);
                            //컨디션은 있지만 모드가 없는경우 추가하는경우
                            hmTempConditions.put(Constants.KEY_ITEM_NAME,
                                    mUtil.getString(mActivity, R.string.layout_rules_edit_08));
                            hmTempConditions.put(Constants.KEY_ITEM_SUB_TYPE_CODE, "02");
                            hmTempConditions.put(Constants.KEY_ITEM_SUB, itemSubList);
                            mConditionList.add(hmTempConditions);
                        }
                        getAlListConditions(0);
                    }
                    break;
                case Constants.ACT_RULES_DATE_SELECT:
                    String date = data.getStringExtra(Constants.EXTRA_DATE);
                    if (!date.equals("")) {
                        Dlog.v("date", date);

                        HashMap<String, Object> itemSubMap = new HashMap<>();
                        String sourceId = "";
                        itemSubMap.put(Constants.KEY_SOURCE_ID, sourceId);
                        String sourceName = "";
                        itemSubMap.put(Constants.KEY_SOURCE_NAME, sourceName);
                        String sourceSubId = "";
                        itemSubMap.put(Constants.KEY_SOURCE_SUB_ID, sourceSubId);
                        String sourceSubName = "";
                        itemSubMap.put(Constants.KEY_SOURCE_SUB_NAME, sourceSubName);
                        String conditionTypeCode = "";
                        itemSubMap.put(Constants.KEY_CONDITION_TYPE_CODE, conditionTypeCode);
                        String conditionTypeCodeName = "";
                        itemSubMap.put(Constants.KEY_CONDITION_TYPE_CODE_NAME, conditionTypeCodeName);
                        itemSubMap.put(Constants.KEY_CMDCLS_VALUE, date);
                        String cmdclsValueMsg = "";
                        itemSubMap.put(Constants.KEY_CMDCLS_VALUE_MSG, cmdclsValueMsg);
                        String unit = "";
                        itemSubMap.put(Constants.KEY_UNIT, unit);
                        String dataTypeCode = "";
                        itemSubMap.put(Constants.KEY_DATA_TYPE_CODE, dataTypeCode);
                        String dayOfWeek = "";
                        itemSubMap.put(Constants.KEY_DAYOFWEEK, dayOfWeek);
                        String repeatable = "";
                        itemSubMap.put(Constants.KEY_REPEATABLE, repeatable);
                        String hour = "";
                        itemSubMap.put(Constants.KEY_HOUR, hour);
                        String minute = "";
                        itemSubMap.put(Constants.KEY_MINUTE, minute);
                        String imageFileName = "";
                        itemSubMap.put(Constants.KEY_IMAGE_FILE_NAME, imageFileName);
                        String deleteYn = "";
                        itemSubMap.put(Constants.KEY_DELETE_YN, deleteYn);

                        ArrayList<HashMap<String, Object>> tempItemSubList = new ArrayList<>();

                        HashMap<String, Object> hmTempConditions = new HashMap<>();
                        Boolean isCheck = false;
                        if (mConditionList.size() > 0) {
                            for (int row = 0; row < mConditionList.size(); row++) {
                                String itemSubTypeCode = mUtil.null2string(mConditionList.get(row)
                                        .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                                if (itemSubTypeCode.equals("21")) {
                                    tempItemSubList = (ArrayList<HashMap<String, Object>>) mConditionList.get(row)
                                            .get(Constants.KEY_ITEM_SUB);
                                    tempItemSubList.clear();
                                    tempItemSubList.add(itemSubMap);
                                    isCheck = true;
                                    break;
                                }
                            }
                        }
                        if (!isCheck) {
                            tempItemSubList.add(itemSubMap);
                            //컨디션은 있지만 날짜가 없는경우 추가하는경우
                            hmTempConditions.put(Constants.KEY_ITEM_NAME,
                                    mUtil.getString(mActivity, R.string.layout_rules_edit_09));
                            hmTempConditions.put(Constants.KEY_ITEM_SUB_TYPE_CODE, "21");
                            hmTempConditions.put(Constants.KEY_ITEM_SUB, tempItemSubList);
                            mConditionList.add(hmTempConditions);
                        }
                        getAlListConditions(0);
                    }
                    break;
                case Constants.ACT_RULES_CONDITION_SELECT:
                    int conditionType = data.getIntExtra(Constants.EXTRA_CONDITION_TYPE, 0);
                    if (Constants.ACT_SPINNER == conditionType) {
                        showModeSpinner();
//                        mUtil.getView(mActivity, R.id.llConditionBody1Title).performClick();
                    } else {
                        onActivityResult(conditionType, resultCode, data);
                    }
                    break;
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                default:
                    break;
            }
        }
    }

    /**
     * Rule json data parsing & set.
     *
     * @param content parsing할 json string
     */
    void setRulesJsonInit(String content) {

        try {
            JSONObject joResult = new JSONObject(content);

            mHomegrpRuleId = mUtil.null2string(joResult.get(Constants.KEY_RULE_ID));
            mRuleName = mUtil.null2string(joResult.get(Constants.KEY_RULE_NAME));
            mUtil.getEditText(mActivity, R.id.edtRulesName).setText(mRuleName);

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

            mConditions = mUtil.null2empty(joResult.get(Constants.KEY_CONDITIONS)).toString();
            mTriggers = mUtil.null2empty(joResult.get(Constants.KEY_TRIGGERS)).toString();
            mActions = mUtil.null2empty(joResult.get(Constants.KEY_ACTIONS)).toString();

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

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

        Dlog.v("mTriggers=", mTriggers);
        mTriggerList.clear();
        mTriggerList = mUtil.jsonToArrayListMap(mTriggers);
        setDispTriggers();
    }

    /**
     * Triggers display.
     */
    @SuppressWarnings("unchecked")
    void setDispTriggers() {

        Dlog.v("alList_Triggers1 = ", mTriggerList.toString());
        mUtil.getLinearLayout(mActivity, R.id.llTrigger).setVisibility(View.VISIBLE);
        mUtil.getView(mActivity, R.id.llTriggerTitle).setSelected(false);
        mUtil.getTextView(mActivity, R.id.tvTriggerTitle)
                .setText(mUtil.getString(mActivity, R.string.layout_rules_edit_04));
        mUtil.getView(mActivity, R.id.ivTriggerAdd).setVisibility(View.VISIBLE);
        mUtil.getLinearLayout(mActivity, R.id.llTriggerBody).removeAllViews();
        if (mTriggerList.size() > 0) {
            //현재로써는 트리거는 단일임 나중에 멀티일때 풀어야 함
            //            for ( int row = 0; row < mTriggerList.size(); row++ ) {
            int row = 0;
            HashMap<String, Object> hmTemp;
            hmTemp = mTriggerList.get(row);
            LinearLayout childView = (LinearLayout) View.inflate(
                    this, R.layout.row_rules_triggers_list, null);
            mUtil.getView(childView, R.id.btnRowDelete).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    deleteConditions(1);
                    mTriggers = mCustomJson;
                    setDispTriggersInit();
                }
            });

            mUtil.getView(childView, R.id.llRowRoot).setTag(row);
            mUtil.getView(childView, R.id.llRowRoot).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Intent intent = new Intent(mActivity, RulesTriggersSelect.class);
                    intent.putExtra(Constants.EXTRA_TRIGGERS, mTriggerList);
                    intent.putExtra(Constants.EXTRA_CONDITIONS, mConditionList);
                    mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_RULES_TRIGGERS_SELECT);
                }
            });

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

            mUtil.getView(mActivity, R.id.llTriggerTitle).setSelected(true);
            mUtil.getView(mActivity, R.id.ivTriggerAdd).setVisibility(View.GONE);
            ArrayList<HashMap<String, Object>> itemSubList;
            if (!mUtil.null2string(hmTemp.get(Constants.KEY_ITEM_SUB)).equals("")) {
                itemSubList = (ArrayList<HashMap<String, Object>>) hmTemp.get(Constants.KEY_ITEM_SUB);
                int row1 = 0;
                switch (itemSubTypeCode) {
                    case "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[] saTime = mUtil.UTCtoLocal6(httpHour + minute);
                        int localHour = mUtil.str2int(saTime[0]);
                        String ampm = (localHour >= 12 ? mUtil.getString(mActivity, R.string.layout_pm)
                                : mUtil.getString(mActivity, R.string.layout_am));
                        String hour = (localHour >= 12 ? mDecimalFormat.format((localHour - (localHour == 12 ? 0 : 12)))
                                : (localHour == 0 ? mDecimalFormat.format(localHour + 12) : saTime[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) + " " + saTime[1]
                                    + mUtil.getString(mActivity, R.string.layout_minute));
                        } else {
                            mUtil.getTextView(childView, R.id.tvRowTitle).setText(hour
                                    + mUtil.getString(mActivity, R.string.layout_hour)
                                    + saTime[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));
                        break;
                    }
                    case "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));
                        break;
                    }
                    case "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));
                        break;
                    }
                    case "01": {
                        //상태가 변할때
                        itemName = mUtil.getString(mActivity, R.string.layout_rules_triggers_select_05);

                        String sourceName = mUtil.null2string(itemSubList.get(row1)
                                .get(Constants.KEY_SOURCE_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));
                            // 삭제된 장치일 경우 트리거 셀렉트화면으로 이동하지 않는다.
                            mUtil.getView(childView, R.id.llRowRoot)
                                    .setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {

                                            mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG900),
                                                    Toast.LENGTH_SHORT);
                                        }
                                    });
                        } else {
                            mUtil.getTextView(childView, R.id.tvRowTitle).setText(sourceName);
                        }
                        String sourceSubName = mUtil.null2string(itemSubList.get(row1)
                                .get(Constants.KEY_SOURCE_SUB_NAME));
                        mUtil.getTextView(childView, R.id.tvRowBody).setText(sourceSubName);
                        mUtil.getTextView(childView, R.id.tvRowState).setVisibility(View.VISIBLE);
                        String conditionTypeCode = mUtil.null2string(itemSubList.get(row)
                                .get(Constants.KEY_CONDITION_TYPE_CODE));
                        String conditionTypeCodeName = mUtil.null2string(itemSubList.get(row)
                                .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 imageFileName = mUtil.null2string(itemSubList.get(row1).get(Constants.KEY_IMAGE_FILE_NAME));
                        mUtil.setImage(mActivity, imageFileName, mUtil.getImageView(childView, R.id.ivRowIcon));
                        break;
                    }
                    default:
                        break;
                }
            }
//            mUtil.getTextView(mActivity, R.id.tvTriggerTitle).setText(itemName);
            mUtil.getLinearLayout(mActivity, R.id.llTriggerBody).addView(childView);
        }
    }

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

        Dlog.v("mActions=", mActions);
        mActionList.clear();
        mActionList = mUtil.jsonToArrayListMap(mActions);
        setDispActions();
    }

    /**
     * Actions display.
     */
    @SuppressWarnings("unchecked")
    void setDispActions() {

        Dlog.v("alList_Actions1 = ", mActionList.toString());
        mUtil.getLinearLayout(mActivity, R.id.llAction).setVisibility(View.VISIBLE);
        mUtil.getLinearLayout(mActivity, R.id.llActionBody).removeAllViews();

//        mUtil.getLinearLayout(mActivity, R.id.llAlram).setVisibility(View.VISIBLE);
//        mUtil.getLinearLayout(mActivity, R.id.llAlramBody).removeAllViews();
        mUtil.getView(mActivity, R.id.ivActionAdd).setVisibility(View.VISIBLE);
//        mUtil.getView(mActivity, R.id.ivAlramAdd).setVisibility(View.VISIBLE);
        mUtil.getView(mActivity, R.id.llActionTitle).setSelected(false);
//        mUtil.getView(mActivity, R.id.llAlramTitle).setSelected(false);
        if (mActionList.size() > 0) {
            for (int row = 0; row < mActionList.size(); row++) {
                HashMap<String, Object> hmTemp;
                hmTemp = mActionList.get(row);

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

                ArrayList<HashMap<String, Object>> itemSubList;
                if (!mUtil.null2string(hmTemp.get(Constants.KEY_ITEM_SUB)).equals("")) {
                    itemSubList = (ArrayList<HashMap<String, Object>>) hmTemp.get(Constants.KEY_ITEM_SUB);
                    if (itemSubTypeCode.equals("01")) {
                        mUtil.getView(mActivity, R.id.llActionTitle).setSelected(true);
                        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.llRowRoot).setTag(row1);
                            mUtil.getView(childView, R.id.llRowRoot).setOnClickListener(new View.OnClickListener() {
                                        int tag = 0;

                                        @Override
                                        public void onClick(View view) {

                                            tag = (int) view.getTag();

                                            for (int row = 0; row < mActionList.size(); row++) {
                                                String itemSubTypeCode = mUtil.null2string(mActionList.get(row)
                                                        .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                                                if (!mUtil.null2string(mActionList.get(row).get(Constants.KEY_ITEM_SUB)).equals("")) {
                                                    ArrayList<HashMap<String, Object>> itemSubList =
                                                            (ArrayList<HashMap<String, Object>>) mActionList.get(row)
                                                                    .get(Constants.KEY_ITEM_SUB);
                                                    if (itemSubTypeCode.equals("01")) {
                                                        String sourceId = mUtil.null2string(itemSubList.get(tag)
                                                                .get(Constants.KEY_SOURCE_ID));
                                                        String sourceSubId = mUtil.null2string(itemSubList.get(tag)
                                                                .get(Constants.KEY_SOURCE_SUB_ID));
                                                        String deleteYn = mUtil.null2string(itemSubList.get(tag)
                                                                .get(Constants.KEY_DELETE_YN));

                                                        if (deleteYn.equals("Y")) {
                                                            mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG900),
                                                                    Toast.LENGTH_SHORT);
                                                            return;
                                                        } else {
                                                            mIntent = new Intent(mActivity, RulesThingsSelect.class);
                                                            mIntent.putExtra(Constants.EXTRA_CALL_TYPE, "2");
                                                            mIntent.putExtra(Constants.EXTRA_TRIGGERS, mTriggerList);
                                                            mIntent.putExtra(Constants.EXTRA_ACTIONS, mActionList);
                                                            mIntent.putExtra(Constants.EXTRA_CONDITIONS, mConditionList);
                                                            mIntent.putExtra(Constants.EXTRA_DEVICE_ID, sourceId);
                                                            mIntent.putExtra(Constants.EXTRA_NODE_ID, sourceSubId);
                                                            mIntent.putExtra(Constants.EXTRA_POSITION, tag);

                                                            mUtil.callActivityForResultNoAnim(mActivity, mIntent,
                                                                    Constants.ACT_RULES_THINGS_SELECT);
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    });

                            mUtil.getView(childView, R.id.btnRowDelete).setTag(row1);
                            mUtil.getView(childView, R.id.btnRowDelete)
                                    .setOnClickListener(new View.OnClickListener() {
                                        int tag = 0;

                                        @Override
                                        public void onClick(View view) {

                                            tag = (int) view.getTag();
                                            for (int row = 0; row < mActionList.size(); row++) {
                                                String itemSubTypeCode = mUtil.null2string(mActionList.get(row)
                                                        .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                                                ArrayList<HashMap<String, Object>> itemSubList;
                                                if (!mUtil.null2string(mActionList.get(row)
                                                        .get(Constants.KEY_ITEM_SUB)).equals("")) {
                                                    itemSubList = (ArrayList<HashMap<String, Object>>) mActionList.get(row)
                                                            .get(Constants.KEY_ITEM_SUB);
                                                    if (itemSubTypeCode.equals("01")) {
                                                        itemSubList.remove(tag);
                                                        if (itemSubList.size() == 0) {
                                                            mActionList.remove(row);
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                            setDispActions();
                                        }
                                    });

                            String deleteYn = mUtil.null2string(itemSubList.get(row1)
                                    .get(Constants.KEY_DELETE_YN));
                            String sourceName = mUtil.null2string(itemSubList.get(row1)
                                    .get(Constants.KEY_SOURCE_NAME));
                            if (deleteYn.equals("Y")) {
                                mUtil.getTextView(childView, R.id.tvRowTitle)
                                        .setText(mUtil.setSpCenterLine(mActivity, sourceName));
                            } else {
                                mUtil.getTextView(childView, R.id.tvRowTitle)
                                        .setText(sourceName);
                            }
                            String sourceSubName = mUtil.null2string(itemSubList.get(row1)
                                    .get(Constants.KEY_SOURCE_SUB_NAME));
                            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));
                            mUtil.getTextView(childView, R.id.tvRowState).setText((cmdclsValueMsg.equals("")
                                    ? cmdclsValue : cmdclsValueMsg) + unit + (
                                    conditionTypeCode.equals("01")
                                            ? ""
                                            : conditionTypeCodeName));

                            String imageFileName = mUtil.null2string(itemSubList.get(row1)
                                    .get(Constants.KEY_IMAGE_FILE_NAME));
                            mUtil.setImage(mActivity, imageFileName, mUtil.getImageView(childView, R.id.ivRowIcon));
                            mUtil.getLinearLayout(mActivity, R.id.llActionBody).addView(childView);
                        }
                    } else if (itemSubTypeCode.equals("03")) {
//                        mUtil.getView(mActivity, R.id.llAlramTitle).setSelected(true);
//                        mUtil.getView(mActivity, R.id.ivAlramAdd).setVisibility(View.GONE);
                        int row1 = 0;
                        /*LinearLayout childView = (LinearLayout) View.inflate(this, R.layout.row_rules_actions_alram_list1, null);

                        mUtil.getView(childView, R.id.btnRowDelete).setTag(row1);
                        mUtil.getView(childView, R.id.btnRowDelete)
                                .setOnClickListener(new View.OnClickListener() {
                                    int tag = 0;

                                    @Override
                                    public void onClick(View view) {

                                        tag = (int) view.getTag();
                                        for (int row = 0; row < mActionList.size(); row++) {
                                            String itemSubTypeCode = mUtil.null2string(mActionList.get(row)
                                                    .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                                            ArrayList<HashMap<String, Object>> itemSubList;
                                            if (!mUtil.null2string(mActionList.get(row)
                                                    .get(Constants.KEY_ITEM_SUB)).equals("")) {
                                                itemSubList = (ArrayList<HashMap<String, Object>>) mActionList.get(row)
                                                        .get(Constants.KEY_ITEM_SUB);
                                                if (itemSubTypeCode.equals("03")) {
                                                    itemSubList.remove(tag);
                                                    if (itemSubList.size() == 0) {
                                                        mActionList.remove(row);
                                                    }
//                                                    mUtil.getView(mActivity, R.id.llAlramTitle).setSelected(false);
                                                    break;
                                                }
                                            }
                                        }
                                        setDispActions();
                                    }
                                });*/
                        String cmdclsValue = mUtil.null2string(itemSubList.get(row1)
                                .get(Constants.KEY_CMDCLS_VALUE));

//                        final EditText edtBody = mUtil.getEditText(childView, R.id.edtRowTitle);
                        mAlarmMsg.setText(cmdclsValue);
                        mAlarmMsg.setTag(row1);
                        /*mAlarmMsg.addTextChangedListener(new TextWatcher() {
                            String previousString = "";

                            @Override
                            public void onTextChanged(CharSequence chars, int start, int before, int count) {
                                if ((before > 0 || count > 0) && !previousString.equals(chars.toString())) {
                                    mRulesNameOk.setVisibility(View.VISIBLE);
                                    mRulesNameAdd.setVisibility(View.GONE);
                                }
                            }

                            @Override
                            public void beforeTextChanged(CharSequence chars, int start, int count, int after) {

                                previousString = chars.toString();
                            }

                            @Override
                            public void afterTextChanged(Editable editable) {

                                if (mAlarmMsg.getLineCount() >= 5) {
                                    mAlarmMsg.setText(previousString);
                                    mAlarmMsg.setSelection(mAlarmMsg.length());
                                } else {
                                    previousString = editable.toString();
                                }

                                int tag = (int) mAlarmMsg.getTag();

                                for (int row = 0; row < mActionList.size(); row++) {
                                    String itemSubTypeCode = mUtil.null2string(mActionList.get(row)
                                            .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                                    if (!mUtil.null2string(mActionList.get(row)
                                            .get(Constants.KEY_ITEM_SUB)).equals("")) {
                                        ArrayList<HashMap<String, Object>> itemSubList =
                                                (ArrayList<HashMap<String, Object>>) mActionList.get(row)
                                                        .get(Constants.KEY_ITEM_SUB);
                                        if (itemSubTypeCode.equals("03")) {
                                            itemSubList.get(tag).put(Constants.KEY_CMDCLS_VALUE, previousString);
                                            break;
                                        }
                                    }
                                }
                            }
                        });*/
//                        mUtil.getLinearLayout(mActivity, R.id.llAlramBody).addView(childView);
                    }
                }
            }
        }
    }

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

        Dlog.v("mActions=", mActions);
        mConditionList.clear();
        mConditionList = mUtil.jsonToArrayListMap(mConditions);
        getAlListConditions(0);
    }

    @SuppressWarnings("unchecked")
    private String getAlListConditions(int type) {
        //        mType   = 1: 요일 담아주기
        String retValue = "";
        if (type == 1) {
            if (mConditionList.size() > 0) {
                for (int row = 0; row < mConditionList.size(); row++) {
                    HashMap<String, Object> hmTemp;
                    hmTemp = mConditionList.get(row);

                    String itemSubTypeCode = mUtil.null2string(hmTemp.get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                    if (itemSubTypeCode.equals("22")) {
                        //요일
                        ArrayList<HashMap<String, Object>> itemSubList;
                        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> tempItemSubMap;
                                tempItemSubMap = itemSubList.get(0);

                                retValue = mUtil.null2string(tempItemSubMap.get(Constants.KEY_CMDCLS_VALUE_MSG));
                            }
                        }
                        break;
                    }
                }
            }
        } else {
            mUtil.getView(mActivity, R.id.llCondition).setVisibility(View.VISIBLE);
            mUtil.getView(mActivity, R.id.llConditionBody).setVisibility(View.GONE);
            mUtil.getView(mActivity, R.id.llConditionTitle).setSelected(false);
//            mUtil.getView(mActivity, R.id.ivConditionBody1TitleAdd).setVisibility(View.VISIBLE);
//            mUtil.getView(mActivity, R.id.ivConditionBody2TitleAdd).setVisibility(View.VISIBLE);
//            mUtil.getView(mActivity, R.id.ivConditionBody3TitleAdd).setVisibility(View.VISIBLE);
            mUtil.getLinearLayout(mActivity, R.id.llConditionBody1).removeAllViews();
            mUtil.getLinearLayout(mActivity, R.id.llConditionBody2).removeAllViews();
            mUtil.getLinearLayout(mActivity, R.id.llConditionBody3).removeAllViews();
            if (mConditionList.size() > 0) {
                //수정필요
                for (int row = 0; row < mConditionList.size(); row++) {
                    HashMap<String, Object> hmTemp;
                    hmTemp = mConditionList.get(row);

                    String itemSubTypeCode = mUtil.null2string(hmTemp.get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                    if (!itemSubTypeCode.equals("22")) {
                        mUtil.getView(mActivity, R.id.llConditionBody).setVisibility(View.VISIBLE);
                        mUtil.getView(mActivity, R.id.llConditionTitle).setSelected(true);
                        ArrayList<HashMap<String, Object>> itemSubList;
                        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) {
                                for (int row1 = 0; row1 < itemSubList.size(); row1++) {
                                    HashMap<String, Object> tempItemSubMap;
                                    tempItemSubMap = itemSubList.get(row1);

                                    LinearLayout childView = (LinearLayout) View.inflate(this, R.layout.row_rules_conditions_list, null);

                                    mUtil.getView(childView, R.id.llRowBody_Body).setVisibility(View.GONE);
                                    mUtil.getView(childView, R.id.tvRowState).setVisibility(View.VISIBLE);

                                    switch (itemSubTypeCode) {
                                        case "02": {
                                            //모드
                                            mUtil.getView(mActivity, R.id.llConditionBody1Title).setVisibility(View.VISIBLE);
                                            mUtil.getView(mActivity, R.id.ivConditionBody1TitleAdd).setVisibility(View.GONE);
                                            mUtil.getView(childView, R.id.vEmp1).setVisibility(View.VISIBLE);

                                            mUtil.getView(childView, R.id.llRowRoot).setTag(row1);
                                            mUtil.getView(childView, R.id.llRowRoot).setOnClickListener(
                                                    new View.OnClickListener() {
                                                        int tag = 0;

                                                        @Override
                                                        public void onClick(View view) {

                                                            tag = (int) view.getTag();

                                                            for (int row = 0; row < mConditionList.size(); row++) {
                                                                String itemSubTypeCode = mUtil.null2string(mConditionList.get(row)
                                                                        .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                                                                if (!mUtil.null2string(mConditionList.get(row)
                                                                        .get(Constants.KEY_ITEM_SUB)).equals("")) {
                                                                    ArrayList<HashMap<String, Object>> itemSubList =
                                                                            (ArrayList<HashMap<String, Object>>) mConditionList.get(row)
                                                                                    .get(Constants.KEY_ITEM_SUB);
                                                                    if (itemSubTypeCode.equals("02")) {
                                                                        mModeCode = mUtil.null2string(itemSubList.get(tag)
                                                                                .get(Constants.KEY_CMDCLS_VALUE));
                                                                        mMode = mUtil.null2string(itemSubList.get(tag)
                                                                                .get(Constants.KEY_SOURCE_SUB_NAME));

                                                                        callModeSpinner();
                                                                        break;
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    });
                                            mUtil.getView(childView, R.id.btnRowDelete).setTag(row1);
                                            mUtil.getView(childView, R.id.btnRowDelete)
                                                    .setOnClickListener(new View.OnClickListener() {
                                                        int tag = 0;

                                                        @Override
                                                        public void onClick(View view) {

                                                            tag = (int) view.getTag();
                                                            for (int row = 0; row < mConditionList.size(); row++) {
                                                                String itemSubTypeCode = mUtil.null2string(mConditionList.get(row)
                                                                        .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                                                                ArrayList<HashMap<String, Object>> itemSubList;
                                                                if (!mUtil.null2string(mConditionList.get(row)
                                                                        .get(Constants.KEY_ITEM_SUB)).equals("")) {
                                                                    itemSubList = (ArrayList<HashMap<String, Object>>)
                                                                            mConditionList.get(row).get(Constants.KEY_ITEM_SUB);
                                                                    if (itemSubTypeCode.equals("02")) {
                                                                        itemSubList.remove(tag);
                                                                        if (itemSubList.size() == 0) {
                                                                            mConditionList.remove(row);
                                                                        }
                                                                        break;
                                                                    }
                                                                }
                                                            }
                                                            getAlListConditions(0);
                                                        }
                                                    });

                                            String cmdclsValueMsg = mUtil.null2string(tempItemSubMap
                                                    .get(Constants.KEY_CMDCLS_VALUE_MSG));

                                            Dlog.v("cmdclsValueMsg", cmdclsValueMsg);
                                            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);
                                            break;
                                        }
                                        case "21": {
                                            //기간
                                            mUtil.getView(mActivity, R.id.llConditionBody2Title).setVisibility(View.VISIBLE);
                                            mUtil.getView(mActivity, R.id.ivConditionBody2TitleAdd).setVisibility(View.GONE);
                                            mUtil.getView(childView, R.id.vEmp1).setVisibility(View.VISIBLE);

                                            mUtil.getView(childView, R.id.llRowRoot).setTag(row1);
                                            mUtil.getView(childView, R.id.llRowRoot)
                                                    .setOnClickListener(new View.OnClickListener() {
                                                        int tag = 0;

                                                        @Override
                                                        public void onClick(View view) {

                                                            tag = (int) view.getTag();

                                                            for (int row = 0; row < mConditionList.size(); row++) {
                                                                String itemSubTypeCode = mUtil.null2string(mConditionList.get(row)
                                                                        .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                                                                if (!mUtil.null2string(mConditionList.get(row)
                                                                        .get(Constants.KEY_ITEM_SUB)).equals("")) {
                                                                    ArrayList<HashMap<String, Object>> itemSubList =
                                                                            (ArrayList<HashMap<String, Object>>) mConditionList.get(row)
                                                                                    .get(Constants.KEY_ITEM_SUB);
                                                                    if (itemSubTypeCode.equals("21")) {
                                                                        String cmdclsValue = mUtil.null2string(itemSubList.get(tag)
                                                                                .get(Constants.KEY_CMDCLS_VALUE));

                                                                        mIntent = new Intent(mActivity, RulesDateSelect.class);
                                                                        mIntent.putExtra(Constants.EXTRA_DATE, cmdclsValue);
                                                                        mUtil.callActivityForResultNoAnim(mActivity, mIntent,
                                                                                Constants.ACT_RULES_DATE_SELECT);
                                                                        break;
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    });
                                            mUtil.getView(childView, R.id.btnRowDelete).setTag(row1);
                                            mUtil.getView(childView, R.id.btnRowDelete)
                                                    .setOnClickListener(new View.OnClickListener() {
                                                        int tag = 0;

                                                        @Override
                                                        public void onClick(View view) {

                                                            tag = (int) view.getTag();
                                                            for (int row = 0; row < mConditionList.size(); row++) {
                                                                String itemSubTypeCode = mUtil.null2string(mConditionList.get(row)
                                                                        .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                                                                ArrayList<HashMap<String, Object>> itemSubList;
                                                                if (!mUtil.null2string(mConditionList.get(row)
                                                                        .get(Constants.KEY_ITEM_SUB)).equals("")) {
                                                                    itemSubList = (ArrayList<HashMap<String, Object>>)
                                                                            mConditionList.get(row).get(Constants.KEY_ITEM_SUB);
                                                                    if (itemSubTypeCode.equals("21")) {
                                                                        itemSubList.remove(tag);
                                                                        if (itemSubList.size() == 0) {
                                                                            mConditionList.remove(row);
                                                                        }
                                                                        break;
                                                                    }
                                                                }
                                                            }
                                                            getAlListConditions(0);
                                                        }
                                                    });
                                            String cmdclsValue = mUtil.null2string(tempItemSubMap
                                                    .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);
                                            break;
                                        }
                                        case "01": {
                                            //장치
                                            mUtil.getView(mActivity, R.id.llConditionBody3Title).setVisibility(View.VISIBLE);
                                            mUtil.getView(childView, R.id.llRowBody_Body).setVisibility(View.VISIBLE);
                                            mUtil.getView(childView, R.id.vEmp1).setVisibility(View.GONE);
                                            mUtil.getView(childView, R.id.llRowRoot).setTag(row1);
                                            mUtil.getView(childView, R.id.llRowRoot)
                                                    .setOnClickListener(new View.OnClickListener() {
                                                        int tag = 0;

                                                        @Override
                                                        public void onClick(View view) {

                                                            tag = (int) view.getTag();

                                                            for (int row = 0; row < mConditionList.size(); row++) {
                                                                String itemSubTypeCode = mUtil.null2string(mConditionList.get(row)
                                                                        .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                                                                if (!mUtil.null2string(mConditionList.get(row)
                                                                        .get(Constants.KEY_ITEM_SUB)).equals("")) {
                                                                    ArrayList<HashMap<String, Object>> itemSubList =
                                                                            (ArrayList<HashMap<String, Object>>) mConditionList.get(row)
                                                                                    .get(Constants.KEY_ITEM_SUB);
                                                                    if (itemSubTypeCode.equals("01")) {
                                                                        String sourceId = mUtil.null2string(itemSubList.get(tag)
                                                                                .get(Constants.KEY_SOURCE_ID));
                                                                        String sourceSubId = mUtil.null2string(itemSubList.get(tag)
                                                                                .get(Constants.KEY_SOURCE_SUB_ID));
                                                                        String deleteYn = mUtil.null2string(itemSubList.get(tag)
                                                                                .get(Constants.KEY_DELETE_YN));

                                                                        if (deleteYn.equals("Y")) {
                                                                            mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG900),
                                                                                    Toast.LENGTH_SHORT);
                                                                            return;
                                                                        } else {
                                                                            mIntent = new Intent(mActivity, RulesThingsSelect.class);
                                                                            mIntent.putExtra(Constants.EXTRA_CALL_TYPE, "3");
                                                                            mIntent.putExtra(Constants.EXTRA_TRIGGERS, mTriggerList);
                                                                            mIntent.putExtra(Constants.EXTRA_ACTIONS, mActionList);
                                                                            mIntent.putExtra(Constants.EXTRA_CONDITIONS, mConditionList);
                                                                            mIntent.putExtra(Constants.EXTRA_DEVICE_ID, sourceId);
                                                                            mIntent.putExtra(Constants.EXTRA_NODE_ID, sourceSubId);
                                                                            mIntent.putExtra(Constants.EXTRA_POSITION, tag);

                                                                            mUtil.callActivityForResultNoAnim(mActivity, mIntent,
                                                                                    Constants.ACT_RULES_THINGS_SELECT);
                                                                        }
                                                                        break;
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    });
                                            mUtil.getView(childView, R.id.btnRowDelete).setTag(row1);
                                            mUtil.getView(childView, R.id.btnRowDelete)
                                                    .setOnClickListener(new View.OnClickListener() {
                                                        int tag = 0;

                                                        @Override
                                                        public void onClick(View view) {

                                                            tag = (int) view.getTag();
                                                            for (int row = 0; row < mConditionList.size(); row++) {
                                                                String itemSubTypeCode = mUtil.null2string(mConditionList.get(row)
                                                                        .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                                                                ArrayList<HashMap<String, Object>> itemSubList;
                                                                if (!mUtil.null2string(mConditionList.get(row)
                                                                        .get(Constants.KEY_ITEM_SUB)).equals("")) {
                                                                    itemSubList = (ArrayList<HashMap<String, Object>>)
                                                                            mConditionList.get(row).get(Constants.KEY_ITEM_SUB);
                                                                    if (itemSubTypeCode.equals("01")) {
                                                                        itemSubList.remove(tag);
                                                                        if (itemSubList.size() == 0) {
                                                                            mConditionList.remove(row);
                                                                        }
                                                                        break;
                                                                    }
                                                                }
                                                            }
                                                            getAlListConditions(0);
                                                        }
                                                    });

                                            String sourceName = mUtil.null2string(tempItemSubMap
                                                    .get(Constants.KEY_SOURCE_NAME));
                                            String deleteYn = mUtil.null2string(tempItemSubMap
                                                    .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);
                                            }
                                            String sourceSubName = mUtil.null2string(tempItemSubMap
                                                    .get(Constants.KEY_SOURCE_SUB_NAME));
                                            mUtil.getTextView(childView, R.id.tvRowBody).setText(sourceSubName);
                                            mUtil.getTextView(childView, R.id.tvRowState).setVisibility(View.VISIBLE);
                                            String conditionTypeCode = mUtil.null2string(tempItemSubMap.get(
                                                    Constants.KEY_CONDITION_TYPE_CODE));
                                            String conditionTypeCodeName = mUtil.null2string(tempItemSubMap.get(
                                                    Constants.KEY_CONDITION_TYPE_CODE_NAME));
                                            String cmdclsValue = mUtil.null2string(tempItemSubMap
                                                    .get(Constants.KEY_CMDCLS_VALUE));
                                            String unit = mUtil.null2string(itemSubList.get(row1)
                                                    .get(Constants.KEY_UNIT));
                                            String cmdclsValueMsg = mUtil.null2string(tempItemSubMap
                                                    .get(Constants.KEY_CMDCLS_VALUE_MSG));
                                            mUtil.getTextView(childView, R.id.tvRowState)
                                                    .setText((cmdclsValueMsg.equals("") ? cmdclsValue : cmdclsValueMsg)
                                                            + unit
                                                            + (conditionTypeCode.equals("01") ? "" : conditionTypeCodeName));

                                            String imageFileName = mUtil.null2string(tempItemSubMap
                                                    .get(Constants.KEY_IMAGE_FILE_NAME));
                                            mUtil.setImage(mActivity, imageFileName,
                                                    mUtil.getImageView(childView, R.id.ivRowIcon));
                                            mUtil.getLinearLayout(mActivity, R.id.llConditionBody3).addView(childView);
                                            break;
                                        }
                                        default:
                                            break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return retValue;
    }

    /**
     * condition delete.
     *
     * @param type 삭제 할 condition mType
     */
    private void deleteConditions(int type) {

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

                    String itemSubtypeCode = mUtil.null2string(hmTemp.get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                    if (itemSubtypeCode.equals("22")) {
                        mConditionList.remove(row);
                        break;
                    }
                }
            }
        }
    }

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_G_RULES_HOMEGRP_RULE_ID:
                    sendGetRulesDetail();
                    break;
                case MSG_COM_G_MODES:
                    sendGetModes();
                    break;
                case MSG_COM_P_RULES:
                    sendPostRules();
                    break;
                case MSG_COM_P_RULES_HOMEGRP_RULE_ID:
                    sendPutRules();
                    break;

                default:
                    break;
            }
            return true;
        }
    }
}
