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

package com.ntels.onecable.view.rules;

import com.ntels.onecable.R;
import com.ntels.onecable.common.Constants;
import com.ntels.onecable.common.c_interface.OnDataSendToReslut;
import com.ntels.onecable.common.http.HttpSend;
import com.ntels.onecable.common.http.Response;
import com.ntels.onecable.common.util.Dlog;
import com.ntels.onecable.common.util.Util;
import com.ntels.onecable.common.widget.CustomActivity;
import com.ntels.onecable.view.dialog.CustomDialog;
import com.ntels.onecable.view.dialog.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.view.LayoutInflater;
import android.view.View;

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

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

  private static final int MSG_COM_G_COMMON_WEATHER_LOCATION_CODES = 1;

  private Util mUtil = new Util();
  private Intent mIntent;
  private Activity mActivity;

  private String mDayOfWeek = "";
  private ArrayList<HashMap<String, Object>> mTriggers = new ArrayList<>();
  private ArrayList<HashMap<String, Object>> mConditions = new ArrayList<>();
  private HashMap<String, Object> mItemSubMap = new HashMap<>();

  /*통신 관련*/
  private int mType = 0;

  private CustomDialog mCustomDialog = new CustomDialog();
  private int mAreaPosition = -1;
  private String mArea = "";
  private String mAreaCode = "";
  private ArrayList<String> mAlAreaTitle = new ArrayList<>();
  private ArrayList<String> mAlAreaId = new ArrayList<>();

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

    super.onCreate(savedInstanceState);

    mActivity = RulesTriggersSun.this;
    mCustomDialog.setOnMsgAlterToResultEvent(this);

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

    this.setContentView(viewToLoad);
    if (null != getIntent()) {
      Intent intent = getIntent();

      mTriggers = (ArrayList<HashMap<String, Object>>)
          intent.getSerializableExtra(Constants.EXTRA_TRIGGERS);
      mConditions = (ArrayList<HashMap<String, Object>>)
          intent.getSerializableExtra(Constants.EXTRA_CONDITIONS);
    }

    displayListView();
  }

  /**
   * 일출/일몰 trigger 가져오기.
   */
  @SuppressWarnings("unchecked")
  void getTriggersSun() {

    if (mTriggers.size() > 0) {
      int row = 0;
      int row1 = 0;
      String itemSubTypeCode = mUtil.null2string(
          mTriggers.get(row).get(Constants.KEY_ITEM_SUB_TYPE_CODE));
      ArrayList<HashMap<String, Object>> itemSubList;
      if (!mUtil.null2string(mTriggers.get(row).get(Constants.KEY_ITEM_SUB)).equals("")) {
        itemSubList = (ArrayList<HashMap<String, Object>>)
            mTriggers.get(row).get(Constants.KEY_ITEM_SUB);
        if (itemSubTypeCode.equals("32")) {
          mItemSubMap = itemSubList.get(row1);

          String sourceSubId = mUtil.null2string(mItemSubMap.get(Constants.KEY_SOURCE_SUB_ID));
          Dlog.v("sunriseUtcTime sourceSubId=" + sourceSubId);
          if (sourceSubId.equals("sunriseUtcTime")) {
            mUtil.getView(mActivity, R.id.btnSun1).setSelected(true);
            mUtil.getView(mActivity, R.id.btnSun2).setSelected(false);
          } else if (sourceSubId.equals("sunsetUtcTime")) {
            mUtil.getView(mActivity, R.id.btnSun1).setSelected(false);
            mUtil.getView(mActivity, R.id.btnSun2).setSelected(true);
          }
          mAreaCode = mUtil.null2string(mItemSubMap.get(Constants.KEY_SOURCE_ID));
          mArea = mUtil.null2string(mItemSubMap.get(Constants.KEY_SOURCE_NAME));
          mUtil.getTextView(mActivity, R.id.tvArea).setText(mArea);
//          mUtil.getViewUnderline(mActivity, R.id.tvArea);
        }
      }
    }
  }

  /**
   * 요일 가져오기.
   */
  @SuppressWarnings("unchecked")
  void getDayOfWeek() {

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

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

              mDayOfWeek = mUtil.null2string(tempItemSubMap.get(Constants.KEY_CMDCLS_VALUE));
            }
          }

          mUtil.getView(mActivity, R.id.llMon).setSelected(false);
          mUtil.getView(mActivity, R.id.llTue).setSelected(false);
          mUtil.getView(mActivity, R.id.llWed).setSelected(false);
          mUtil.getView(mActivity, R.id.llThu).setSelected(false);
          mUtil.getView(mActivity, R.id.llFri).setSelected(false);
          mUtil.getView(mActivity, R.id.llSat).setSelected(false);
          mUtil.getView(mActivity, R.id.llSun).setSelected(false);
          if (!mDayOfWeek.equals("")) {
            String[] strArray = mDayOfWeek.split("\\,", 100);
            for (String s : strArray) {
              switch (s) {
                case "MON":
                  mUtil.getView(mActivity, R.id.llMon).setSelected(true);
                  break;
                case "TUE":
                  mUtil.getView(mActivity, R.id.llTue).setSelected(true);
                  break;
                case "WED":
                  mUtil.getView(mActivity, R.id.llWed).setSelected(true);
                  break;
                case "THU":
                  mUtil.getView(mActivity, R.id.llThu).setSelected(true);
                  break;
                case "FRI":
                  mUtil.getView(mActivity, R.id.llFri).setSelected(true);
                  break;
                case "SAT":
                  mUtil.getView(mActivity, R.id.llSat).setSelected(true);
                  break;
                case "SUN":
                  mUtil.getView(mActivity, R.id.llSun).setSelected(true);
                  break;
                default:
                  break;
              }
            }
          }
          break;
        }
      }
    }
  }

  /**
   * 요일 설정하기.
   *
   * @return 설정 여부
   */
  private Boolean setsDayOfWeek() {

    String tempDayOfWeek = "";
    if (mUtil.getView(mActivity, R.id.llMon).isSelected()) {
      if (!tempDayOfWeek.equals("")) {
        tempDayOfWeek = tempDayOfWeek + ",";
      }
      tempDayOfWeek = tempDayOfWeek + "MON";
    }
    if (mUtil.getView(mActivity, R.id.llTue).isSelected()) {
      if (!tempDayOfWeek.equals("")) {
        tempDayOfWeek = tempDayOfWeek + ",";
      }
      tempDayOfWeek = tempDayOfWeek + "TUE";
    }
    if (mUtil.getView(mActivity, R.id.llWed).isSelected()) {
      if (!tempDayOfWeek.equals("")) {
        tempDayOfWeek = tempDayOfWeek + ",";
      }
      tempDayOfWeek = tempDayOfWeek + "WED";
    }
    if (mUtil.getView(mActivity, R.id.llThu).isSelected()) {
      if (!tempDayOfWeek.equals("")) {
        tempDayOfWeek = tempDayOfWeek + ",";
      }
      tempDayOfWeek = tempDayOfWeek + "THU";
    }
    if (mUtil.getView(mActivity, R.id.llFri).isSelected()) {
      if (!tempDayOfWeek.equals("")) {
        tempDayOfWeek = tempDayOfWeek + ",";
      }
      tempDayOfWeek = tempDayOfWeek + "FRI";
    }
    if (mUtil.getView(mActivity, R.id.llSat).isSelected()) {
      if (!tempDayOfWeek.equals("")) {
        tempDayOfWeek = tempDayOfWeek + ",";
      }
      tempDayOfWeek = tempDayOfWeek + "SAT";
    }
    if (mUtil.getView(mActivity, R.id.llSun).isSelected()) {
      if (!tempDayOfWeek.equals("")) {
        tempDayOfWeek = tempDayOfWeek + ",";
      }
      tempDayOfWeek = tempDayOfWeek + "SUN";
    }
    if (tempDayOfWeek.equals("")) {
      mCustomDialog.msgAlert(mActivity, Constants.MSG855);
      return false;
    }

    String[] alItem = mUtil.getStringArrayValues(mActivity, "DAYOFWEEK_ITEM");
    String[] alText = mUtil.getStringArrayValues(mActivity, "DAYOFWEEK_TEXT");
    String tempDayOfWeek1 = tempDayOfWeek;
    String[] strArray = tempDayOfWeek.split("\\,", 100);
    for (String s : strArray) {
      int idx = mUtil.getArraryFind(alItem, s);
      tempDayOfWeek1 = tempDayOfWeek1.replaceAll(s, alText[idx]);
    }

    HashMap<String, Object> tempItemSubMap = new HashMap<String, Object>();

    String tempSourceId = "";
    tempItemSubMap.put(Constants.KEY_SOURCE_ID, tempSourceId);
    String tempSourceSubId = "";
    tempItemSubMap.put(Constants.KEY_SOURCE_SUB_ID, tempSourceSubId);
    String tempConditionTypeCode = "09";
    tempItemSubMap.put(Constants.KEY_CONDITION_TYPE_CODE, tempConditionTypeCode);
    String tempCmdclsValue = tempDayOfWeek;
    tempItemSubMap.put(Constants.KEY_CMDCLS_VALUE, tempCmdclsValue);
    String tempCmdclsValueMsg = tempDayOfWeek1;
    tempItemSubMap.put(Constants.KEY_CMDCLS_VALUE_MSG, tempCmdclsValueMsg);

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

    HashMap<String, Object> hmTempCondition = new HashMap<String, Object>();
    hmTempCondition.put(Constants.KEY_ITEM_NAME, "");
    hmTempCondition.put(Constants.KEY_ITEM_SUB_TYPE_CODE, "22");
    hmTempCondition.put(Constants.KEY_ITEM_SUB, tempItemSubList);

    boolean isSet = false;
    if (mConditions.size() > 0) {
      for (int row = 0; row < mConditions.size(); row++) {
        HashMap<String, Object> hmTemp;
        hmTemp = mConditions.get(row);

        String itemSubTypeCode = mUtil.null2string(hmTemp.get(Constants.KEY_ITEM_SUB_TYPE_CODE));
        if (itemSubTypeCode.equals("22")) {
          mConditions.set(row, hmTempCondition);
          isSet = true;
          break;
        }
      }

      if (!isSet) {
        mConditions.add(hmTempCondition);
      }
    } else {
      mConditions.add(hmTempCondition);
    }

    return true;
  }


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

//    mUtil.getTextView(mActivity, R.id.tvArea).setText(mUtil.getString(mActivity, R.string.layout_selected));
//    mUtil.getViewUnderline(mActivity, R.id.tvArea);
    mUtil.getView(mActivity, R.id.btnSun1).setSelected(true);
    mUtil.getView(mActivity, R.id.btnSun2).setSelected(false);
    mUtil.getView(mActivity, R.id.tvArea).setOnClickListener(this);
    mUtil.getView(mActivity, R.id.btnSun1).setOnClickListener(this);
    mUtil.getView(mActivity, R.id.btnSun2).setOnClickListener(this);
    mUtil.getView(mActivity, R.id.llMon).setOnClickListener(this);
    mUtil.getView(mActivity, R.id.llTue).setOnClickListener(this);
    mUtil.getView(mActivity, R.id.llWed).setOnClickListener(this);
    mUtil.getView(mActivity, R.id.llThu).setOnClickListener(this);
    mUtil.getView(mActivity, R.id.llFri).setOnClickListener(this);
    mUtil.getView(mActivity, R.id.llSat).setOnClickListener(this);
    mUtil.getView(mActivity, R.id.llSun).setOnClickListener(this);
    mUtil.getView(mActivity, R.id.llBtn1).setOnClickListener(this);
    mUtil.getView(mActivity, R.id.llBtn2).setOnClickListener(this);
    mUtil.getView(mActivity, R.id.llMon).setSelected(true);
    mUtil.getView(mActivity, R.id.llTue).setSelected(true);
    mUtil.getView(mActivity, R.id.llWed).setSelected(true);
    mUtil.getView(mActivity, R.id.llThu).setSelected(true);
    mUtil.getView(mActivity, R.id.llFri).setSelected(true);
    mUtil.getView(mActivity, R.id.llSat).setSelected(true);
    mUtil.getView(mActivity, R.id.llSun).setSelected(true);

    getTriggersSun();

    getDayOfWeek();


    comHandler.sendMessageDelayed(comHandler.obtainMessage(
        MSG_COM_G_COMMON_WEATHER_LOCATION_CODES), Constants.HANDLER_DELAY_MILLIS);
  }

  @Override
  public void onClick(View view) {

    switch (view.getId()) {
      case R.id.llBtn1:
        if (mAreaPosition == -1) {
          mCustomDialog.msgAlert(mActivity, Constants.MSG860);
          return;
        }
        if (setsDayOfWeek()) {
          String sourceId = "";
          String sourceName = "";
          if (mAreaPosition > -1) {
            sourceId = mUtil.null2string(mAlAreaId.get(mAreaPosition));
            sourceName = mUtil.null2string(mAlAreaTitle.get(mAreaPosition));
          } else {
            mCustomDialog.msgAlert(mActivity, Constants.MSG860);
            return;
          }
          String sourceSubId = "";
          String sourceSubName = "";
          if (mUtil.getView(mActivity, R.id.btnSun1).isSelected()) {
            sourceSubId = "sunriseUtcTime";
            sourceSubName = mUtil.getString(mActivity, R.string.layout_rules_triggers_sun_02);
          } else {
            sourceSubId = "sunsetUtcTime";
            sourceSubName = mUtil.getString(mActivity, R.string.layout_rules_triggers_sun_03);
          }

          mItemSubMap.put(Constants.KEY_SOURCE_ID, sourceId);
          mItemSubMap.put(Constants.KEY_SOURCE_NAME, sourceName);
          mItemSubMap.put(Constants.KEY_SOURCE_SUB_ID, sourceSubId);
          mItemSubMap.put(Constants.KEY_SOURCE_SUB_NAME, sourceSubName);
          String conditionTypeCode = "";
          mItemSubMap.put(Constants.KEY_CONDITION_TYPE_CODE, conditionTypeCode);
          String cmdclsValue = "";
          mItemSubMap.put(Constants.KEY_CMDCLS_VALUE, cmdclsValue);
          String dataTypeCode = "";
          mItemSubMap.put(Constants.KEY_DATA_TYPE_CODE, dataTypeCode);
          String dayOfWeek = "";
          mItemSubMap.put(Constants.KEY_DAYOFWEEK, dayOfWeek);
          String repeatable = "";
          mItemSubMap.put(Constants.KEY_REPEATABLE, repeatable);
          String hour = "";
          mItemSubMap.put(Constants.KEY_HOUR, hour);
          String minute = "";
          mItemSubMap.put(Constants.KEY_MINUTE, minute);

          ArrayList<HashMap<String, Object>> itemSubList = new ArrayList<>();
          itemSubList.clear();
          itemSubList.add(mItemSubMap);

          mTriggers.clear();

          HashMap<String, Object> hmTriggers = new HashMap<String, Object>();
          hmTriggers.put(Constants.KEY_ITEM_SUB, itemSubList);
          hmTriggers.put(Constants.KEY_ITEM_NAME,
              mUtil.getString(mActivity, R.string.layout_rules_triggers_select_03));
          hmTriggers.put(Constants.KEY_ITEM_SUB_TYPE_CODE, "32");

          mTriggers.add(hmTriggers);

          mIntent = new Intent();
          mIntent.putExtra(Constants.EXTRA_TRIGGERS, mTriggers);
          mIntent.putExtra(Constants.EXTRA_CONDITIONS, mConditions);
          mActivity.setResult(RESULT_OK, mIntent);
          finish();
        }
        break;
      case R.id.llBtn2:
        onBackPressed();
        break;
      case R.id.btnSun1:
        mUtil.getView(mActivity, R.id.btnSun1).setSelected(true);
        mUtil.getView(mActivity, R.id.btnSun2).setSelected(false);
        break;
      case R.id.btnSun2:
        mUtil.getView(mActivity, R.id.btnSun1).setSelected(false);
        mUtil.getView(mActivity, R.id.btnSun2).setSelected(true);
        break;
      case R.id.tvArea:
        mIntent = new Intent();
        mIntent.setClass(mActivity, DialogSpinner.class);
        mIntent.putExtra(Constants.EXTRA_SPINNER_LIST1, mAlAreaTitle);
        mIntent.putExtra(Constants.EXTRA_SPINNER_TITLE,
            mUtil.getString(mActivity, R.string.layout_rules_location_select_01));
        mIntent.putExtra(Constants.EXTRA_SPINNER_TYPE, 0);
        mIntent.putExtra(Constants.EXTRA_SPINNER_SHOW_TYPE, 1);
        mIntent.putExtra(Constants.EXTRA_SPINNER_POSITION, mAreaPosition);
        mUtil.callActivityForResult(mActivity, mIntent, Constants.ACT_SPINNER, Constants.CHANGE_EVENT_BOTTOM_BOTTOM);
        break;
      case R.id.llMon:
      case R.id.llTue:
      case R.id.llWed:
      case R.id.llThu:
      case R.id.llFri:
      case R.id.llSat:
      case R.id.llSun:
        if (view.isSelected()) {
          view.setSelected(false);
        } else {
          view.setSelected(true);
        }
        break;
      default:
        break;
    }
  }

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

  class IncomingHandlerCallBack implements Handler.Callback {

    @Override
    public boolean handleMessage(Message msg) {

      mType = msg.what;
      switch (msg.what) {
        case MSG_COM_G_COMMON_WEATHER_LOCATION_CODES:
          sendGetCommonWeatherLocationCodes();
          break;

        default:
          break;
      }
      return true;
    }
  }

  /**
   * 야후날씨 지역코드 목록 조회(야후 날씨에 사용할 지역코드목록을 조회한다) 요청.
   */
  private void sendGetCommonWeatherLocationCodes() {

    try {
      HttpSend httpSend;

      httpSend = new HttpSend(mActivity);

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

          resultGetCommonWeatherLocationCodes(result);
        }
      });
      httpSend.getCommonWeatherLocationCode();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  /**
   * {@link RulesTriggersSun#sendGetCommonWeatherLocationCodes() 지역코드} 요청 결과.
   *
   * @param response 결과 data
   */
  private void resultGetCommonWeatherLocationCodes(Response response) {

    try {
      if (response.getStatusCode() == 200) {
        ArrayList<HashMap<String, Object>> alList = mUtil.jsonToArrayListMap(response.getContent());
        if (alList.size() > 0) {
          for (int row = 0; row < alList.size(); row++) {
            HashMap<String, Object> hmTemp;
            hmTemp = alList.get(row);
            String commonCode = mUtil.null2string(hmTemp.get(Constants.KEY_COMMON_CODE));
            String commonCodeName = mUtil.null2string(hmTemp.get(Constants.KEY_COMMON_CODE_NAME));
            mAlAreaId.add(commonCode);
            mAlAreaTitle.add(commonCodeName);
            if (commonCode.equals(mAreaCode)) {
              mAreaPosition = row;
              String area = mUtil.null2string(mAlAreaTitle.get(mAreaPosition));
              mUtil.getTextView(mActivity, R.id.tvArea).setText(area);
//              mUtil.getViewUnderline(mActivity, R.id.tvArea);
            }
          }
        }
      } else {
        JSONObject joResult = new JSONObject(response.getContent());
        Dlog.v(joResult.toString());
//                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_ERR_CODE));
        String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
//                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));
        String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

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

  @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.MSG805:
        if (btnResult == 1) {
          // mComHandler.sendMessage(mComHandler.obtainMessage(MSG_COM_DOLOGOUT));
        }
        break;

      default:
        break;
    }
  }

  @Override
  public void onBackPressed() {

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

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

    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
      switch (requestCode) {
        case Constants.ACT_SPINNER:
          if (mAreaPosition != data.getIntExtra(Constants.EXTRA_SPINNER_RESULT, 0)) {
            mAreaPosition = data.getIntExtra(Constants.EXTRA_SPINNER_RESULT, 0);
            mArea = mUtil.null2string(mAlAreaTitle.get(mAreaPosition));
            mUtil.getTextView(mActivity, R.id.tvArea).setText(mArea);
//            mUtil.getViewUnderline(mActivity, R.id.tvArea);
          }
          break;
        default:
          break;
      }
    } else {
      switch (requestCode) {
        default:
          break;
      }
    }
  }
}
