/*
 * 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.ListInterface;
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.view.dialog.CustomDialog;
import com.ntels.onecable.view.dialog.DialogSpinner;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

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

import jp.wasabeef.recyclerview.adapters.AlphaInAnimationAdapter;
import jp.wasabeef.recyclerview.adapters.ScaleInAnimationAdapter;

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

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

  private static final int MSG_COM_G_RULES_ITEM_DEVICES_ITEM_TYPE_CODE = 1;

  private Util util = new Util();
  private Intent intent;
  private Activity act;

  private CustomDialog customDialog = new CustomDialog();
  private String callType = "";
  private ArrayList<HashMap<String, Object>> triggers = new ArrayList<>();
  private ArrayList<HashMap<String, Object>> conditions = new ArrayList<>();
  private ArrayList<HashMap<String, Object>> actions = new ArrayList<>();
  private int devicesPosition = -1;
  private int selectedPosition = -1;
  private String devicesSelectTitle = "";
  private String itemTypeCode = "";
  private String deviceId = "";
  private String nodeId = "";
  private ArrayList<String> devicesTitle = new ArrayList<>();
  private ArrayList<String> devicesId = new ArrayList<>();
  private ArrayList<String> devicesImage = new ArrayList<>();
  private ArrayList<String> devicesViewImage = new ArrayList<>();
  private ArrayList<HashMap<String, Object>> totalList = new ArrayList<>();

  int screenType = 0;
  /*통신 관련*/
  private ArrayList<HashMap<String, Object>> alAllTotalList = new ArrayList<>();
  private int type = 0;
  private RulesThingsSelectAdapter dataAdapter;
  private RecyclerView rcvList;
  private boolean isListHeader = false;
  private boolean isListFooter = false;
  private int isListColumnsCnt = 1;
  private GridLayoutManager gridLayoutManager;
  private int selectPosition = -1;

  @SuppressWarnings("unchecked")
  @Override
  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    act = RulesThingsSelect.this;
    customDialog.setOnMsgAlterToResultEvent(this);

    View viewToLoad = LayoutInflater.from(act).inflate(R.layout.rules_things_select, null);
    this.setContentView(viewToLoad);
    if (null != getIntent()) {
      Intent intent = getIntent();

      //1:트리거, 2:액션, 3:컨디션, 4:모드
      callType = util.null2string(intent.getStringExtra(Constants.EXTRA_CALL_TYPE));
      deviceId = util.null2string(intent.getStringExtra(Constants.EXTRA_DEVICE_ID));
      nodeId = util.null2string(intent.getStringExtra(Constants.EXTRA_NODE_ID));
      selectedPosition = intent.getIntExtra(Constants.EXTRA_POSITION, 0);
      triggers = (ArrayList<HashMap<String, Object>>)
          intent.getSerializableExtra(Constants.EXTRA_TRIGGERS);
      conditions = (ArrayList<HashMap<String, Object>>)
          intent.getSerializableExtra(Constants.EXTRA_CONDITIONS);
      actions = (ArrayList<HashMap<String, Object>>)
          intent.getSerializableExtra(Constants.EXTRA_ACTIONS);
    }

    displayListView();
  }

  /**
   * UI display.
   */
  @SuppressWarnings("unchecked")
  private void displayListView() {

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

    util.setKeyboardHide(act, util.getLinearLayout(act, R.id.llPageRoot));
    //        util.setKeyboardHide(mActivity, util.getLinearLayout(mActivity, R.id.llBodyList));
    util.getView(act, R.id.llPageRoot).setVisibility(View.INVISIBLE);

    if (callType.equals("1")) {
      itemTypeCode = "01";
      devicesSelectTitle = util.getString(act, R.string.layout_rules_triggers_select_05);
    } else if (callType.equals("2")) {
      itemTypeCode = "02";
      devicesSelectTitle = util.getString(act, R.string.layout_rules_edit_04);
    } else if (callType.equals("3")) {
      itemTypeCode = "01";
      if (AppConfig.getLanguageType().equals(Locale.ENGLISH.toString())) {
        devicesSelectTitle = util.getString(act, R.string.layout_rules_edit_09).substring(4);
      } else {
        devicesSelectTitle = util.getString(act, R.string.layout_rules_edit_09);
      }
    } else if (callType.equals("4")) {
      itemTypeCode = "02";
      devicesSelectTitle = util.getString(act, R.string.layout_rules_edit_04);
    }

    isListFooter = false;
    dataAdapter = new RulesThingsSelectAdapter(act, R.layout.row_rules_things_select, R.layout.row_rules_things_select, R.layout.row_rules_things_select, totalList, this);
    dataAdapter.setFooterCheck(isListFooter);

    rcvList = (RecyclerView) act.findViewById(R.id.rcvList);
    isListColumnsCnt = 1;
    if (isListColumnsCnt == 1) {
      rcvList.setLayoutManager(new LinearLayoutManager(act));
    } else {
      gridLayoutManager = new GridLayoutManager(act, isListColumnsCnt, GridLayoutManager.VERTICAL, false);
      gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {

          int positionType = dataAdapter.getItemViewType(position);
          int totalCount = dataAdapter.getItemCount();
          int valueCount = dataAdapter.getItemCount();
          if (isListHeader) {
            valueCount = totalCount - 1;
          }

          if (positionType == dataAdapter.TYPE_HEADER) {
            return gridLayoutManager.getSpanCount();
          } else {
            return dataAdapter.getItemViewType(position) == 1 ? 1 : (valueCount % isListColumnsCnt == 1 ? gridLayoutManager.getSpanCount() : 1);
          }
        }
      });
      rcvList.setLayoutManager(gridLayoutManager);
    }

    AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(dataAdapter);
    alphaAdapter.setDuration(150);
    ScaleInAnimationAdapter scaleAdapter = new ScaleInAnimationAdapter(alphaAdapter);
    scaleAdapter.setDuration(150);
    rcvList.setAdapter(scaleAdapter);

    comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_RULES_ITEM_DEVICES_ITEM_TYPE_CODE), 10);
  }

  @Override
  public void onClick(View view) {

    switch (view.getId()) {
      case R.id.llBtn1:
        Boolean isSelectCheck = false;
        int tempSelectRow = -1;
        for (int row = 0; row < totalList.size(); row++) {
          Dlog.v("irow cnt =", row);
          if (totalList.get(row).get(Constants.KEY_SELECT_YN).equals("Y")) {
            tempSelectRow = row;
            isSelectCheck = true;
          }
        }
        if (!isSelectCheck) {
          util.setShowToast(act, util.getString(act, R.string.MSG850), Toast.LENGTH_SHORT);
          return;
        } else {
          String sourceSubId = util.null2string(totalList.get(tempSelectRow).get(Constants.KEY_SOURCE_SUB_ID));
          String sourceSubName = util.null2string(totalList.get(tempSelectRow).get(Constants.KEY_SOURCE_SUB_NAME));
          String unit = util.null2string(totalList.get(tempSelectRow).get(Constants.KEY_UNIT));
          String dataTypeCode = util.null2string(totalList.get(tempSelectRow).get(Constants.KEY_DATA_TYPE_CODE));
          String cmdclsValue = util.null2string(totalList.get(tempSelectRow).get(Constants.KEY_CMDCLS_VALUE));
          String cmdclsValueMsg = util.null2string(totalList.get(tempSelectRow).get(Constants.KEY_CMDCLS_VALUE_MSG));
          String conditionTypeCode = util.null2string(totalList.get(tempSelectRow).get(Constants.KEY_CONDITION_TYPE_CODE));
          String conditionTypeCodeName = util.null2string(totalList.get(tempSelectRow).get(Constants.KEY_CONDITION_TYPE_CODE_NAME));

          if (cmdclsValue.equals("")) {
            util.setShowToast(act, util.getString(act, R.string.MSG826), Toast.LENGTH_SHORT);
            return;
          }

          HashMap<String, Object> itemSubMap = new HashMap<>();
          String sourceId = devicesId.get(devicesPosition);
          itemSubMap.put(Constants.KEY_SOURCE_ID, sourceId);
          String sourceName = devicesTitle.get(devicesPosition);
          itemSubMap.put(Constants.KEY_SOURCE_NAME, sourceName);
          itemSubMap.put(Constants.KEY_SOURCE_SUB_ID, sourceSubId);
          itemSubMap.put(Constants.KEY_SOURCE_SUB_NAME, sourceSubName);
          itemSubMap.put(Constants.KEY_CONDITION_TYPE_CODE, conditionTypeCode);
          itemSubMap.put(Constants.KEY_CONDITION_TYPE_CODE_NAME, conditionTypeCodeName);
          itemSubMap.put(Constants.KEY_CMDCLS_VALUE, cmdclsValue);
          itemSubMap.put(Constants.KEY_CMDCLS_VALUE_MSG, cmdclsValueMsg);
          itemSubMap.put(Constants.KEY_UNIT, unit);
          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 = devicesViewImage.get(devicesPosition);
          itemSubMap.put(Constants.KEY_IMAGE_FILE_NAME, imageFileName);
          String availableYn = "";
          itemSubMap.put(Constants.KEY_AVAILABLE_YN, availableYn);

          ArrayList<HashMap<String, Object>> tempItemSubList = new ArrayList<HashMap<String, Object>>();
          if (callType.equals("1")) {
            tempItemSubList.clear();
            tempItemSubList.add(itemSubMap);
            triggers.clear();

            HashMap<String, Object> hmTriggers = new HashMap<>();
            hmTriggers.put(Constants.KEY_ITEM_SUB, tempItemSubList);
            hmTriggers.put(Constants.KEY_ITEM_NAME,
                util.getString(act, R.string.layout_rules_triggers_select_05));
            hmTriggers.put(Constants.KEY_ITEM_SUB_TYPE_CODE, "01");

            triggers.add(hmTriggers);
          } else if (callType.equals("2")) {
            itemSubMap.put(Constants.KEY_ACTION_TYPE_CODE, "00");
            HashMap<String, Object> hmTempActions = new HashMap<String, Object>();
            if (actions.size() > 0) {
              Boolean isCheck = false;
              for (int row = 0; row < actions.size(); row++) {
                String itemSubTypeCode = util.null2string(actions.get(row).get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                if (itemSubTypeCode.equals("01")) {
                  if (!util.null2string(actions.get(row).get(Constants.KEY_ITEM_SUB)).equals("")) {
                    tempItemSubList = (ArrayList<HashMap<String, Object>>)
                        actions.get(row).get(Constants.KEY_ITEM_SUB);
                    if (deviceId.equals("")) {
                      //액션은 있지만 선택하지 않고 추가하는경우
                      tempItemSubList.add(itemSubMap);
                    } else {
                      //액션은 있고 선택한 경우
                      tempItemSubList.set(selectedPosition, itemSubMap);
                    }
                    isCheck = true;
                    break;
                  }
                }
              }
              if (!isCheck) {
                //액션은 있지만 선택하지 않고 디바이스액션이 없는경우 추가하는경우(메세지만 있는경우)
                tempItemSubList.add(itemSubMap);
                hmTempActions.put(Constants.KEY_ITEM_NAME, util.getString(act, R.string.layout_rules_detail_03));
                hmTempActions.put(Constants.KEY_ITEM_SUB_TYPE_CODE, "01");
                hmTempActions.put(Constants.KEY_ITEM_SUB, tempItemSubList);
                actions.add(hmTempActions);
              }
            } else {
              //액션이 아예 없는 경우
              tempItemSubList.add(itemSubMap);
              hmTempActions.put(Constants.KEY_ITEM_NAME, util.getString(act, R.string.layout_rules_detail_03));
              hmTempActions.put(Constants.KEY_ITEM_SUB_TYPE_CODE, "01");
              hmTempActions.put(Constants.KEY_ITEM_SUB, tempItemSubList);
              actions.add(hmTempActions);
            }
          } else if (callType.equals("3")) {
            itemSubMap.put(Constants.KEY_ACTION_TYPE_CODE, "00");
            HashMap<String, Object> hmTempConditions = new HashMap<String, Object>();
            if (conditions.size() > 0) {
              Boolean isCheck = false;
              for (int row = 0; row < conditions.size(); row++) {
                String itemSubTypeCode = util.null2string(conditions.get(row)
                    .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                if (itemSubTypeCode.equals("01")) {
                  if (!util.null2string(conditions.get(row)
                      .get(Constants.KEY_ITEM_SUB)).equals("")) {
                    tempItemSubList = (ArrayList<HashMap<String, Object>>)
                        conditions.get(row).get(Constants.KEY_ITEM_SUB);
                    if (deviceId.equals("")) {
                      //액션은 있지만 선택하지 않고 추가하는경우
                      tempItemSubList.add(itemSubMap);
                    } else {
                      //액션은 있고 선택한 경우
                      tempItemSubList.set(selectedPosition, itemSubMap);
                    }
                    isCheck = true;
                    break;
                  }
                }
              }
              if (!isCheck) {
                //액션은 있지만 선택하지 않고 디바이스액션이 없는경우 추가하는경우(메세지만 있는경우)
                tempItemSubList.add(itemSubMap);
                hmTempConditions.put(Constants.KEY_ITEM_NAME, util.getString(act, R.string.layout_rules_detail_08));
                hmTempConditions.put(Constants.KEY_ITEM_SUB_TYPE_CODE, "01");
                hmTempConditions.put(Constants.KEY_ITEM_SUB, tempItemSubList);
                conditions.add(hmTempConditions);
              }
            } else {
              //액션이 아예 없는 경우
              tempItemSubList.add(itemSubMap);
              hmTempConditions.put(Constants.KEY_ITEM_NAME, util.getString(act, R.string.layout_rules_detail_03));
              hmTempConditions.put(Constants.KEY_ITEM_SUB_TYPE_CODE, "01");
              hmTempConditions.put(Constants.KEY_ITEM_SUB, tempItemSubList);
              conditions.add(hmTempConditions);
            }
          } else if (callType.equals("4")) {
            itemSubMap.put(Constants.KEY_ACTION_TYPE_CODE, "00");
            HashMap<String, Object> hmTempActions = new HashMap<String, Object>();
            if (actions.size() > 0) {
              Boolean isCheck = false;
              for (int row = 0; row < actions.size(); row++) {
                String itemSubTypeCode = util.null2string(actions.get(row)
                    .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                if (itemSubTypeCode.equals("01")) {
                  if (!util.null2string(actions.get(row).get(Constants.KEY_ITEM_SUB)).equals("")) {
                    tempItemSubList = (ArrayList<HashMap<String, Object>>)
                        actions.get(row).get(Constants.KEY_ITEM_SUB);
                    if (deviceId.equals("")) {
                      //액션은 있지만 선택하지 않고 추가하는경우
                      tempItemSubList.add(itemSubMap);
                    } else {
                      //액션은 있고 선택한 경우
                      tempItemSubList.set(selectedPosition, itemSubMap);
                    }
                    isCheck = true;
                    break;
                  }
                }
              }
              if (!isCheck) {
                //액션은 있지만 선택하지 않고 디바이스액션이 없는경우 추가하는경우(메세지만 있는경우)
                tempItemSubList.add(itemSubMap);
                hmTempActions.put(Constants.KEY_ITEM_NAME, util.getString(act, R.string.layout_rules_detail_03));
                hmTempActions.put(Constants.KEY_ITEM_SUB_TYPE_CODE, "01");
                hmTempActions.put(Constants.KEY_ITEM_SUB, tempItemSubList);
                actions.add(hmTempActions);
              }
            } else {
              //액션이 아예 없는 경우
              tempItemSubList.add(itemSubMap);
              hmTempActions.put(Constants.KEY_ITEM_NAME, util.getString(act, R.string.layout_rules_detail_03));
              hmTempActions.put(Constants.KEY_ITEM_SUB_TYPE_CODE, "01");
              hmTempActions.put(Constants.KEY_ITEM_SUB, tempItemSubList);
              actions.add(hmTempActions);
            }
          }
          intent = new Intent();
          intent.putExtra(Constants.EXTRA_TRIGGERS, triggers);
          intent.putExtra(Constants.EXTRA_ACTIONS, actions);
          intent.putExtra(Constants.EXTRA_CONDITIONS, conditions);
          act.setResult(RESULT_OK, intent);
          finish();
        }
        break;
      case R.id.llBtn2:
        onBackPressed();
        break;
      default:
        break;
    }
  }

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

    switch (msgId) {

      case Constants.MSG998:
        util.callApp_Start(act, "LOGOUT");
        break;
      case Constants.MSG997:
        util.callApp_Start(act, "HOME_RELOAD");
        break;
      case Constants.MSG807:
        if (btnResult == 1) {
          comHandler.sendMessage(
              comHandler.obtainMessage(MSG_COM_G_RULES_ITEM_DEVICES_ITEM_TYPE_CODE));
        } else {
          onBackPressed();
        }
        break;
      default:
        break;
    }
  }

  @Override
  public void onBackPressed() {

    if (screenType == 1) {
      screenType = 0;
      devicesPosition = -1;
      util.getView(act, R.id.llPageRoot).setVisibility(View.INVISIBLE);
      callDevicesList();
    } else {
      intent = new Intent();
      act.setResult(RESULT_CANCELED, intent);
      finish();
    }
  }

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

    intent = new Intent();
    intent.setClass(act, DialogSpinner.class);
    intent.putExtra(Constants.EXTRA_SPINNER_LIST1, devicesTitle);
    intent.putExtra(Constants.EXTRA_SPINNER_ICON_LIST, devicesImage);

    intent.putExtra(Constants.EXTRA_SPINNER_TITLE, devicesSelectTitle);
    intent.putExtra(Constants.EXTRA_SPINNER_TYPE, 0);
    intent.putExtra(Constants.EXTRA_SPINNER_POSITION, devicesPosition);
    util.callActivityForResultNoAnim(act, intent, Constants.ACT_SPINNER);
  }

  Handler comHandler = new Handler(new IncomingHandlerCallBack());

  class IncomingHandlerCallBack implements Handler.Callback {

    @Override
    public boolean handleMessage(Message msg) {

      type = msg.what;
      switch (msg.what) {
        case MSG_COM_G_RULES_ITEM_DEVICES_ITEM_TYPE_CODE:
          //dialog_show();
          sendGetActionDevices();
          break;

        default:
          break;
      }
      return true;
    }
  }

  /**
   * 액션 장치의 목록 조회(규칙 아이템(조건,액션)으로 사용할 장치를 조회) 요청.
   */
  private void sendGetActionDevices() {

    try {
      HttpSend httpSend;

      httpSend = new HttpSend(act);

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

          resultGetActionDevices(result);
        }
      });

      httpSend.G_rules_item_devices_item_type_code(itemTypeCode);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  /**
   * 액션 장치의 목록 조회(규칙 아이템(조건,액션)으로 사용할 장치를 조회) 요청 결과.
   *
   * @param result 결과 data
   */
  private void resultGetActionDevices(Response result) {

    try {
      if (result.getStatusCode() == 200) {
        ArrayList<HashMap<String, Object>> alList = util.jsonToArrayListMap(result.getContent());
        if (alList.size() > 0) {
          for (int row = 0; row < alList.size(); row++) {
            HashMap<String, Object> hmTemp;
            hmTemp = alList.get(row);
            alAllTotalList.add(hmTemp);

            String sourceId = util.null2string(hmTemp.get(Constants.KEY_SOURCE_ID));
            String sourceName = util.null2string(hmTemp.get(Constants.KEY_SOURCE_NAME));
            String imageFileName = util.null2string(hmTemp.get(Constants.KEY_IMAGE_FILE_NAME));
            String imageFileViewName = util.null2string(
                hmTemp.get(Constants.KEY_IMAGE_FILE_VIEW_NAME));
            devicesId.add(sourceId);
            devicesTitle.add(sourceName);
            devicesImage.add(imageFileName);
            devicesViewImage.add(imageFileViewName);
          }
        }

        if (deviceId.equals("")) {
          callDevicesList();
        } else {
          for (int row1 = 0; row1 < devicesId.size(); row1++) {
            if (devicesId.get(row1).equals(deviceId)) {
              devicesPosition = row1;
              util.getView(act, R.id.llPageRoot).setVisibility(View.VISIBLE);
              setDispNodes();
              break;
            }
          }
        }
      } else {
        JSONObject joResult = new JSONObject(result.getContent());
        Dlog.v(joResult.toString());
        String errorCode = util.null2string(joResult.get(Constants.KEY_ERR_CODE));
        String errorMsg = util.null2string(joResult.get(Constants.KEY_ERR_MSG));

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

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

    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
      switch (requestCode) {
        case Constants.ACT_SPINNER:
          int tempDevicesPosition = data.getIntExtra(Constants.EXTRA_SPINNER_RESULT, -1);
          if (tempDevicesPosition == -1) {
            util.setShowToast(act, util.getString(act, R.string.MSG827), Toast.LENGTH_SHORT);
            callDevicesList();
            break;
          } else {
            screenType = 1;
            util.getView(act, R.id.llPageRoot).setVisibility(View.VISIBLE);
            devicesPosition = tempDevicesPosition;
            setDispNodes();
          }
          break;
        case Constants.ACT_RULES_MULTISENSOR_SELECT:
          String tempMultiSensor = data.getStringExtra(Constants.EXTRA_MULTISENSOR);
          String conditionTypeCode = data.getStringExtra(Constants.EXTRA_CONDITION_TYPE_CODE);
          String conditionTypeCodeName = "";
          String itemTypeCode = data.getStringExtra(Constants.EXTRA_ITEM_TYPE_CODE);
          if (!"02".equals(itemTypeCode)) {
            if (conditionTypeCode.equals("03")) {
              conditionTypeCodeName = util.getString(act, R.string.layout_sequentes);
            } else {
              conditionTypeCodeName = util.getString(act, R.string.layout_over);
            }
          }
          Dlog.v("tempMultiSensor =" + tempMultiSensor);
          Dlog.v("conditionTypeCode =" + conditionTypeCode);
          Dlog.v("conditionTypeCodeName =" + conditionTypeCodeName);
          totalList.get(selectPosition).put(Constants.KEY_CMDCLS_VALUE, tempMultiSensor);
          totalList.get(selectPosition).put(Constants.KEY_CONDITION_TYPE_CODE, conditionTypeCode);
          totalList.get(selectPosition).put(Constants.KEY_CONDITION_TYPE_CODE_NAME,
              conditionTypeCodeName);
          dataAdapter.notifyDataSetChanged();
          break;
        case Constants.ACT_RULES_COLOR_SELECT:
          String selectedHsbColor = data.getStringExtra(Constants.EXTRA_SELECTED_COLOR);
          LogUtil.i(TAG, "selectedColor =" + selectedHsbColor);
          totalList.get(selectPosition).put(Constants.KEY_CMDCLS_VALUE, selectedHsbColor);
          dataAdapter.notifyDataSetChanged();
        default:
          break;
      }
    } else {
      switch (requestCode) {
        case Constants.ACT_SPINNER:
          intent = new Intent();
          act.setResult(RESULT_CANCELED, intent);
          finish();
          break;
        default:
          break;
      }
    }
  }

  /**
   * Node display.
   */
  @SuppressWarnings("unchecked")
  void setDispNodes() {

    HashMap<String, Object> hmTemp;
    hmTemp = alAllTotalList.get(devicesPosition);

    String tempSourceId = util.null2string(hmTemp.get(Constants.KEY_SOURCE_ID));
    String tempSourceName = util.null2string(hmTemp.get(Constants.KEY_SOURCE_NAME));
    String tempImageFileName = util.null2string(hmTemp.get(Constants.KEY_IMAGE_FILE_NAME));
    String tempImageFileViewName = util.null2string(
        hmTemp.get(Constants.KEY_IMAGE_FILE_VIEW_NAME));

    //아이콘
    util.setImage(act, tempImageFileName, R.id.ivTitleIcon);
    //디바이스명
    util.getTextView(act, R.id.tvTitle).setText(tempSourceName);

    totalList.clear();
    if (!util.null2string(hmTemp.get(Constants.KEY_ITEM_SUB)).equals("")) {
      ArrayList<HashMap<String, Object>> itemSubList1 =
          (ArrayList<HashMap<String, Object>>) hmTemp.get(Constants.KEY_ITEM_SUB);
      int defaultPosition = -1;
      for (int row1 = 0; row1 < itemSubList1.size(); row1++) {
        HashMap<String, Object> tempMap1;
        tempMap1 = itemSubList1.get(row1);
        String sourceSubId = util.null2string(itemSubList1.get(row1)
            .get(Constants.KEY_SOURCE_SUB_ID));

        Dlog.v("nodeId = " + nodeId);
        Dlog.v("sourceSubId = " + sourceSubId);
        if (sourceSubId.equals(nodeId)) {
          String selectCmdclsValue = "";
          String selectCmdclsValueMsg = "";
          String selectConditionTypeCode = "";
          String selectConditionTypeCodeName = "";

          ArrayList<HashMap<String, Object>> tempItemSubList;
          switch (callType) {
            case "1":
              if (triggers.size() > 0) {
                if (!util.null2string(triggers.get(0).get(Constants.KEY_ITEM_SUB)).equals("")) {
                  tempItemSubList = (ArrayList<HashMap<String, Object>>) triggers.get(0)
                      .get(Constants.KEY_ITEM_SUB);
                  selectCmdclsValue = util.null2string(tempItemSubList.get(selectedPosition)
                      .get(Constants.KEY_CMDCLS_VALUE));
                  selectCmdclsValueMsg = util.null2string(tempItemSubList.get(selectedPosition)
                      .get(Constants.KEY_CMDCLS_VALUE_MSG));
                  selectConditionTypeCode = util.null2string(tempItemSubList.get(selectedPosition)
                      .get(Constants.KEY_CONDITION_TYPE_CODE));
                  selectConditionTypeCodeName = util.null2string(tempItemSubList
                      .get(selectedPosition).get(Constants.KEY_CONDITION_TYPE_CODE_NAME));
                }
              }
              break;
            case "2":
              if (actions.size() > 0) {
                for (int row = 0; row < actions.size(); row++) {
                  String itemSubTypeCode = util.null2string(actions.get(row)
                      .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                  if (itemSubTypeCode.equals("01")) {
                    if (!util.null2string(actions.get(row)
                        .get(Constants.KEY_ITEM_SUB)).equals("")) {
                      tempItemSubList = (ArrayList<HashMap<String, Object>>) actions.get(row)
                          .get(Constants.KEY_ITEM_SUB);
                      selectCmdclsValue = util.null2string(tempItemSubList.get(selectedPosition)
                          .get(Constants.KEY_CMDCLS_VALUE));
                      selectCmdclsValueMsg = util.null2string(tempItemSubList.get(selectedPosition)
                          .get(Constants.KEY_CMDCLS_VALUE_MSG));
                      selectConditionTypeCode = util.null2string(tempItemSubList
                          .get(selectedPosition).get(Constants.KEY_CONDITION_TYPE_CODE));
                      selectConditionTypeCodeName = util.null2string(tempItemSubList
                          .get(selectedPosition).get(Constants.KEY_CONDITION_TYPE_CODE_NAME));
                      break;
                    }
                  }
                }
              }
              break;
            case "3":
              if (conditions.size() > 0) {
                for (int row = 0; row < conditions.size(); row++) {
                  String itemSubTypeCode = util.null2string(conditions.get(row)
                      .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                  if (itemSubTypeCode.equals("01")) {
                    if (!util.null2string(conditions.get(row)
                        .get(Constants.KEY_ITEM_SUB)).equals("")) {
                      tempItemSubList = (ArrayList<HashMap<String, Object>>) conditions.get(row)
                          .get(Constants.KEY_ITEM_SUB);
                      selectCmdclsValue = util.null2string(tempItemSubList.get(selectedPosition)
                          .get(Constants.KEY_CMDCLS_VALUE));
                      selectCmdclsValueMsg = util.null2string(tempItemSubList.get(selectedPosition)
                          .get(Constants.KEY_CMDCLS_VALUE_MSG));
                      selectConditionTypeCode = util.null2string(tempItemSubList
                          .get(selectedPosition).get(Constants.KEY_CONDITION_TYPE_CODE));
                      selectConditionTypeCodeName = util.null2string(tempItemSubList
                          .get(selectedPosition).get(Constants.KEY_CONDITION_TYPE_CODE_NAME));
                      break;
                    }
                  }
                }
              }
              break;
            case "4":
              if (actions.size() > 0) {
                for (int row = 0; row < actions.size(); row++) {
                  String itemSubTypeCode = util.null2string(actions.get(row)
                      .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                  if (itemSubTypeCode.equals("01")) {
                    if (!util.null2string(actions.get(row)
                        .get(Constants.KEY_ITEM_SUB)).equals("")) {
                      tempItemSubList = (ArrayList<HashMap<String, Object>>) actions.get(row)
                          .get(Constants.KEY_ITEM_SUB);
                      selectCmdclsValue = util.null2string(tempItemSubList.get(selectedPosition)
                          .get(Constants.KEY_CMDCLS_VALUE));
                      selectCmdclsValueMsg = util.null2string(tempItemSubList.get(selectedPosition)
                          .get(Constants.KEY_CMDCLS_VALUE_MSG));
                      selectConditionTypeCode = util.null2string(tempItemSubList
                          .get(selectedPosition).get(Constants.KEY_CONDITION_TYPE_CODE));
                      selectConditionTypeCodeName = util.null2string(tempItemSubList
                          .get(selectedPosition).get(Constants.KEY_CONDITION_TYPE_CODE_NAME));
                      break;
                    }
                  }
                }
              }
              break;
            default:
              break;
          }
          itemSubList1.get(row1).put(Constants.KEY_CMDCLS_VALUE, selectCmdclsValue);
          itemSubList1.get(row1).put(Constants.KEY_CMDCLS_VALUE_MSG, selectCmdclsValueMsg);
          itemSubList1.get(row1).put(Constants.KEY_CONDITION_TYPE_CODE, selectConditionTypeCode);
          itemSubList1.get(row1).put(Constants.KEY_CONDITION_TYPE_CODE_NAME,
              selectConditionTypeCodeName);
          defaultPosition = row1;
        }

        if (defaultPosition != row1) {
          if (callType.equals("2")) {
            if (actions.size() > 0) {
              for (int tempRow = 0; tempRow < actions.size(); tempRow++) {
                String itemSubTypeCode = util.null2string(actions.get(tempRow)
                    .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                if (itemSubTypeCode.equals("01")) {
                  if (!util.null2string(actions.get(tempRow)
                      .get(Constants.KEY_ITEM_SUB)).equals("")) {
                    ArrayList<HashMap<String, Object>> tempItemSubList =
                        (ArrayList<HashMap<String, Object>>) actions.get(tempRow).get(
                        Constants.KEY_ITEM_SUB);
                    for (int tempRow1 = 0; tempRow1 < tempItemSubList.size(); tempRow1++) {
                      String tempHttpSourceId = util.null2string(tempItemSubList.get(tempRow1)
                          .get(Constants.KEY_SOURCE_ID));
                      String tempHttpSourceSubId = util.null2string(tempItemSubList.get(tempRow1)
                          .get(Constants.KEY_SOURCE_SUB_ID));
                      if (tempSourceId.equals(tempHttpSourceId)
                          && sourceSubId.equals(tempHttpSourceSubId)) {
                        tempMap1.put(Constants.KEY_DISABLE_YN, "Y");
                        break;
                      }
                    }
                  }
                  break;
                }
              }
            }
          } else if (callType.equals("3")) {
            if (conditions.size() > 0) {
              for (int tempRow = 0; tempRow < conditions.size(); tempRow++) {
                String itemSubTypeCode = util.null2string(conditions.get(tempRow)
                    .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                if (itemSubTypeCode.equals("01")) {
                  if (!util.null2string(conditions.get(tempRow)
                      .get(Constants.KEY_ITEM_SUB)).equals("")) {
                    ArrayList<HashMap<String, Object>> tempItemSubList =
                        (ArrayList<HashMap<String, Object>>) conditions.get(tempRow).get(
                        Constants.KEY_ITEM_SUB);
                    for (int tempRow1 = 0; tempRow1 < tempItemSubList.size(); tempRow1++) {
                      String tempHttpSourceId = util.null2string(tempItemSubList.get(tempRow1)
                          .get(Constants.KEY_SOURCE_ID));
                      String tempHttpSourceSubId = util.null2string(tempItemSubList.get(tempRow1)
                          .get(Constants.KEY_SOURCE_SUB_ID));
                      if (tempSourceId.equals(tempHttpSourceId)
                          && sourceSubId.equals(tempHttpSourceSubId)) {
                        tempMap1.put(Constants.KEY_DISABLE_YN, "Y");
                        break;
                      }
                    }
                  }
                  break;
                }
              }
            }
          } else if (callType.equals("4")) {
            if (actions.size() > 0) {
              for (int tempRow = 0; tempRow < actions.size(); tempRow++) {
                String itemSubTypeCode = util.null2string(actions.get(tempRow)
                    .get(Constants.KEY_ITEM_SUB_TYPE_CODE));
                if (itemSubTypeCode.equals("01")) {
                  if (!util.null2string(actions.get(tempRow)
                      .get(Constants.KEY_ITEM_SUB)).equals("")) {
                    ArrayList<HashMap<String, Object>> tempItemSubList =
                        (ArrayList<HashMap<String, Object>>) actions.get(tempRow).get(
                        Constants.KEY_ITEM_SUB);
                    for (int tempRow1 = 0; tempRow1 < tempItemSubList.size(); tempRow1++) {
                      String tempHttpSourceId = util.null2string(tempItemSubList.get(tempRow1)
                          .get(Constants.KEY_SOURCE_ID));
                      String tempHttpSourceSubId = util.null2string(tempItemSubList.get(tempRow1)
                          .get(Constants.KEY_SOURCE_SUB_ID));
                      if (tempSourceId.equals(tempHttpSourceId)
                          && sourceSubId.equals(tempHttpSourceSubId)) {
                        tempMap1.put(Constants.KEY_DISABLE_YN, "Y");
                        break;
                      }
                    }
                  }
                  break;
                }
              }
            }
          }
        }
        if (defaultPosition == row1) {
          tempMap1.put(Constants.KEY_SELECT_YN, "Y");
        } else {
          tempMap1.put(Constants.KEY_SELECT_YN, "N");
        }
        totalList.add(tempMap1);
      }
    }
    dataAdapter.notifyDataSetChanged();
    rcvList.getLayoutParams().height = util.getScaleVal(act, 115) * dataAdapter.getItemCount();
  }

  @Override
  public void onListReload() {

  }

  @Override
  public void onLogout() {

  }

  @Override
  public void onCallAction(int callType, int position) {

    switch (callType) {
      case 1:
        // 멀티센서 선택
        selectPosition = position;
        String sourceSubName = util.null2string(totalList.get(selectPosition)
            .get(Constants.KEY_SOURCE_SUB_NAME));
        String controlMinValue = util.null2string(totalList.get(selectPosition)
            .get(Constants.KEY_CONTROL_MIN_VALUE));
        String controlMaxValue = util.null2string(totalList.get(selectPosition)
            .get(Constants.KEY_CONTROL_MAX_VALUE));
        String controlStep = util.null2string(totalList.get(selectPosition)
            .get(Constants.KEY_CONTROL_STEP));
        String unit = util.null2string(totalList.get(selectPosition)
            .get(Constants.KEY_UNIT));
        String cmdclsValue = util.null2string(totalList.get(selectPosition)
            .get(Constants.KEY_CMDCLS_VALUE));
        String conditionTypeCode = util.null2string(totalList.get(selectPosition)
            .get(Constants.KEY_CONDITION_TYPE_CODE));
        intent = new Intent();
        intent.setClass(act, RulesMultiSensorSelect.class);
        intent.putExtra(Constants.EXTRA_NAME, sourceSubName);
        intent.putExtra(Constants.EXTRA_MULTISENSOR, cmdclsValue);
        intent.putExtra(Constants.EXTRA_CONDITION_TYPE_CODE, conditionTypeCode);
        intent.putExtra(Constants.EXTRA_MIN, util.str2int(controlMinValue));
        intent.putExtra(Constants.EXTRA_MAX, util.str2int(controlMaxValue));
        intent.putExtra(Constants.EXTRA_STEP, util.str2int(controlStep));
        intent.putExtra(Constants.EXTRA_UNIT, unit);
        intent.putExtra(Constants.EXTRA_ITEM_TYPE_CODE, itemTypeCode);
        util.callActivityForResultNoAnim(act, intent, Constants.ACT_RULES_MULTISENSOR_SELECT);
        break;
      case 2:
        // Led Bulb 컬러 변경 선택
        intent = new Intent();
        intent.setClass(act, RulesColorSelect.class);
        selectPosition = position;
        String sourceSubName2 = util.null2string(totalList.get(selectPosition)
                .get(Constants.KEY_SOURCE_SUB_NAME));
        intent.putExtra(Constants.EXTRA_NAME, sourceSubName2);
        util.callActivityForResultNoAnim(act, intent, Constants.ACT_RULES_COLOR_SELECT);
        break;
      default:
        break;
    }
  }
}
