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

package com.ntels.kneet.v3.view.mainmore;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ntels.kneet.v3.R;
import com.ntels.kneet.v3.common.AppConfig;
import com.ntels.kneet.v3.common.Constants;
import com.ntels.kneet.v3.common.c_interface.OnDataSendToReslut;
import com.ntels.kneet.v3.common.http.HttpSend;
import com.ntels.kneet.v3.common.http.Response;
import com.ntels.kneet.v3.common.util.Dlog;
import com.ntels.kneet.v3.common.util.LogUtil;
import com.ntels.kneet.v3.common.util.Util;
import com.ntels.kneet.v3.common.widget.CustomActivity;
import com.ntels.kneet.v3.view.dialog.CustomDialog;

import org.json.JSONObject;

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

/**
 * <pre>
 * 1. ClassName :   MainMore
 * 2. FileName  :   MainMore.java
 * 3. Package   :   com.ntels.kneet.v3.view.mainmore
 * 4. Date      :   2016-12-01
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class MainMore extends CustomActivity implements View.OnClickListener,
    CustomDialog.OnMsgAlterToResult {

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

  private static final int MSG_COM_G_DASHBOARD = 1;
  private static final int MSG_COM_P_HOMEGRP_PROFILE_IMAGE = 3;

  private AppConfig appConfig;
  private Util util = new Util();
  private CustomDialog customDialog = new CustomDialog();
  private Intent intent;
  private Activity act;
  private int type = 0;

  private String fileName = "";
  ArrayList<HashMap<String, Object>> modeList = new ArrayList<>();
  private boolean loading = false;
  private SwipeRefreshLayout swipeRefreshLayout;

  @Override
  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

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

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

    displayListView();
  }

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

    util.getView(act, R.id.llNotice).setOnClickListener(this);
    util.getView(act, R.id.llMessagecenter).setOnClickListener(this);
    util.getView(act, R.id.llHomeGateway).setOnClickListener(this);
    util.getView(act, R.id.llSetting).setOnClickListener(this);
    util.getView(act, R.id.llHomeMode1).setOnClickListener(this);
    util.getView(act, R.id.llHomeMode2).setOnClickListener(this);
    util.getView(act, R.id.llHomeMode3).setOnClickListener(this);
    util.getView(act, R.id.llHomeMode4).setOnClickListener(this);
    util.getView(act, R.id.ivClose).setOnClickListener(this);
    util.getView(act, R.id.btnReload).setOnClickListener(this);
    util.getTextView(act, R.id.tvNoticeCnt).setVisibility(View.GONE);
    util.getTextView(act, R.id.tvMessagecenterCnt).setVisibility(View.GONE);

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

        if (!loading) {
          loading = true;
          comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DASHBOARD), 10);
        }
      }
    });
    setHomeHubState();
    comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DASHBOARD), 10);
  }

  /**
   * 홈허브 Off시 아이콘 표시.
   */
  private void setHomeHubState() {

    if (appConfig.getSelect_Homegrp_Homehub_Online_State().equals("OFF")) {
      util.getView(act, R.id.ivHomeGatewayState).setVisibility(View.VISIBLE);
    } else {
      util.getView(act, R.id.ivHomeGatewayState).setVisibility(View.GONE);
    }
  }

  @Override
  public void onConfigurationChanged(Configuration newConfig) {

    super.onConfigurationChanged(newConfig);
  }

  @Override
  public void onClick(View view) {

    switch (view.getId()) {
      case R.id.btnReload:
        view.setEnabled(false);
        comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DASHBOARD), 10);
        break;
      case R.id.llNotice:
        intent = new Intent(act, Notice.class);
        util.callActivityForResult(act, intent, Constants.ACT_NOTICE);
        break;
      case R.id.llMessagecenter:
        intent = new Intent(act, MessageCenter.class);
        util.callActivityForResult(act, intent, Constants.ACT_MESSAGE_CENTER);
        break;
      case R.id.llHomeGateway:
        intent = new Intent(act, Homehub.class);
        util.callActivityForResult(act, intent, Constants.ACT_HOMEHUB);
        break;
      case R.id.llSetting:
        intent = new Intent(act, Setting.class);
        util.callActivityForResult(act, intent, Constants.ACT_SETTING);
        break;
      case R.id.llHomeMode1:
        break;
      case R.id.llHomeMode2:
        break;
      case R.id.llHomeMode3:
        break;
      case R.id.llHomeMode4:
        break;
      case R.id.ivClose:
        onBackPressed();
        break;
      default:
        break;
    }
  }

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

  class IncomingHandlerCallBack implements Handler.Callback {

    @Override
    public boolean handleMessage(Message msg) {

      type = msg.what;
      if (!appConfig.getLogin()) {
        return true;
      }
      switch (msg.what) {
        case MSG_COM_G_DASHBOARD:
          sendGetDashboard();
          break;
        case MSG_COM_P_HOMEGRP_PROFILE_IMAGE:
          sendPostHomegrpProfileImage();
          break;
        default:
          break;
      }
      return true;
    }
  }

  /**
   * 홈그룹 이미지 변경(홈그룹의 프로필 이미지를 수정) 요청.
   */
  private void sendPostHomegrpProfileImage() {

    try {
      HttpSend httpSend = new HttpSend(act);
      httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
        @Override
        public void resultResponse(Response result) {

          resultPostHomegrpProfileImage(result);
        }
      });

      //공통 변수 입력
      httpSend.P_homegrp_profile_image(Constants.HTTP_image_file, fileName);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  /**
   * {@link #sendPostHomegrpProfileImage()} 요청 결과.
   *
   * @param response 결과 data
   */
  private void resultPostHomegrpProfileImage(Response response) {

    try {
      if (response.getStatusCode() == 200) {
        JSONObject joResult = new JSONObject(response.getContent());
        Dlog.v(joResult.toString());

        //회원 번호
        fileName = util.null2string(joResult.get(Constants.HTTP_image_file_name));
      } else {
        JSONObject joResult = new JSONObject(response.getContent());
        Dlog.v(joResult.toString());
        String errorCode = util.null2string(joResult.get(Constants.HTTP_err_code));
        String errorMsg = util.null2string(joResult.get(Constants.HTTP_err_msg));

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

  /**
   * 대시보드 정보 조회(홈그룹 모드 조회, 공지, 알림 갯수 조회 등) 요청.
   */
  private void sendGetDashboard() {

    try {
      HttpSend httpSend = new HttpSend(act, !swipeRefreshLayout.isRefreshing());
      httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
        @Override
        public void resultResponse(Response result) {

          resultGetDashboard(result);
        }
      });

      Dlog.v("util.getPreferences(mActivity, \"notice_read_datetime\")",
          util.getPreferences(act, "notice_read_datetime"));
      //공통 변수 입력
      httpSend.G_dashboard(util.getPreferences(act, "notice_read_datetime"));
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  /**
   * {@link #sendGetDashboard()} 요청 결과.
   *
   * @param response 결과 data
   */
  private void resultGetDashboard(Response response) {

    try {
      if (response.getStatusCode() == 200) {
        JSONObject joResult = new JSONObject(response.getContent());
        String noticeCount = util.null2string(joResult.get(Constants.HTTP_notice_count));
        String pushCount = util.null2string(joResult.get(Constants.HTTP_push_count));
        if (noticeCount.equals("0")) {
          util.getTextView(act, R.id.tvNoticeCnt).setVisibility(View.GONE);
        } else {
          util.getTextView(act, R.id.tvNoticeCnt).setVisibility(View.VISIBLE);
          util.getTextView(act, R.id.tvNoticeCnt).setText(noticeCount);
        }
        if (pushCount.equals("0")) {
          util.getTextView(act, R.id.tvMessagecenterCnt).setVisibility(View.GONE);
        } else {
          util.getTextView(act, R.id.tvMessagecenterCnt).setVisibility(View.VISIBLE);
          util.getTextView(act, R.id.tvMessagecenterCnt).setText(pushCount);
        }

        String modeList = "";
        if (joResult.has(Constants.HTTP_mode_list)) {
          modeList = util.null2string(joResult.get(Constants.HTTP_mode_list));
        }

        if (appConfig.getSelect_Homegrp_Homehub_Device_Id().equals("")) {
          util.getView(act, R.id.llHomeGateway).setEnabled(false);
        } else {
          util.getView(act, R.id.llHomeGateway).setEnabled(true);
        }
        this.modeList = util.jsonToArrayListMap(modeList);
        if (this.modeList.size() > 0) {
          for (int row = 0; row < this.modeList.size(); row++) {
            HashMap<String, Object> tempMap;
            tempMap = this.modeList.get(row);

            String modeId = util.null2string(tempMap.get(Constants.HTTP_mode_id));
            String modeName = util.null2string(tempMap.get(Constants.HTTP_mode_name));
            String useYn = util.null2string(tempMap.get(Constants.HTTP_use_yn));
            final String tempImageFileName = util.null2string(
                tempMap.get(Constants.HTTP_image_file_name));
            final String tempImageFileActiveName = util.null2string(
                tempMap.get(Constants.HTTP_image_file_active_name));
            final String tempImageFileDisableName = util.null2string(
                tempMap.get(Constants.HTTP_image_file_disable_name));

            View view = util.getView(act, util.getIDvalues(act, "llHomeMode" + (row + 1)));
            TextView tvTempImageView = util.getTextView(
                act, util.getIDvalues(act, "tvHomeModeIcon" + (row + 1)));
            final ImageView ivTempImageView = util.getImageView(
                act, util.getIDvalues(act, "ivHomeModeIcon" + (row + 1)));

            tvTempImageView.setText(modeName);
            if (appConfig.getSelect_Homegrp_Homehub_Device_Id().equals("")) {
              view.setEnabled(false);
              util.setImage(act, tempImageFileDisableName, ivTempImageView);
            } else {
              view.setEnabled(true);
              if (useYn.equals("Y")) {
                view.setSelected(true);
                util.setImage(act, tempImageFileActiveName, ivTempImageView);
              } else {
                view.setSelected(false);
                util.setImage(act, tempImageFileName, ivTempImageView);
              }

              view.setTag(row);
              view.setOnClickListener(new View.OnClickListener() {
                int tag = 0;

                @Override
                public void onClick(View view) {

                  tag = (int) view.getTag();
                  if (appConfig.getSelect_Homegrp_Homehub_Online_State().equals("ON")) {

                    intent = new Intent(act, Homemode.class);

                    String tempModeId = util.null2string(
                        MainMore.this.modeList.get(tag).get(Constants.HTTP_mode_id));
                    intent.putExtra(Constants.EXTRA_MODE_ID, tempModeId);
                    String tempBasicModeCode = util.null2string(
                        MainMore.this.modeList.get(tag).get(Constants.HTTP_basic_mode_code));
                    LogUtil.i(TAG, "EXTRA_BASIC_MODE_CODE : " + tempBasicModeCode);
                    intent.putExtra(Constants.EXTRA_BASIC_MODE_CODE, tempBasicModeCode);
                    String tempImageFileViewName = util.null2string(
                        MainMore.this.modeList.get(tag).get(Constants.HTTP_image_file_view_name));
                    intent.putExtra(Constants.EXTRA_MODE_ICON, tempImageFileViewName);
                    String tempImageFileActiveName = util.null2string(
                        MainMore.this.modeList.get(tag).get(Constants.HTTP_image_file_active_name));
                    intent.putExtra(Constants.EXTRA_MODE_ICON1, tempImageFileActiveName);
                    String tempModeName = util.null2string(
                        MainMore.this.modeList.get(tag).get(Constants.HTTP_mode_name));
                    intent.putExtra(Constants.EXTRA_MODE_NAME, tempModeName);
                    String tempHomegrpSceneId = util.null2string(
                        MainMore.this.modeList.get(tag).get(Constants.HTTP_homegrp_rule_id));
                    intent.putExtra(Constants.EXTRA_HOMEGRP_RULE_ID, tempHomegrpSceneId);
                    String tempDeleteCnt = util.null2string(
                        MainMore.this.modeList.get(tag).get(Constants.HTTP_delete_cnt));
                    intent.putExtra(Constants.EXTRA_MODE_DEL_YN, tempDeleteCnt);
                    util.callActivityForResult(act, intent, Constants.ACT_HOMEMODE);
                  } else {
                    util.setShowToast(act, util.getString(act, R.string.MSG866),
                        Toast.LENGTH_SHORT);
                    return;
                  }
                }
              });
            }
          }
        }

        loading = false;
        swipeRefreshLayout.setRefreshing(false);
      } else {
        JSONObject joResult = new JSONObject(response.getContent());
        Dlog.v(joResult.toString());
        String errorCode = util.null2string(joResult.get(Constants.HTTP_err_code));
        String errorMsg = util.null2string(joResult.get(Constants.HTTP_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);
    }
    try {
      util.getView(act, R.id.btnReload).setEnabled(true);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

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

    switch (msgId) {

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

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

    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
      switch (requestCode) {
        case Constants.ACT_HOMEMODE:
        case Constants.ACT_HOMEHUB:
          if (data == null) {
            return;
          }
          Boolean isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
          if (isReload) {
            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DASHBOARD), 10);
          }
          break;
        case Constants.ACT_SETTING:
          break;
        case Constants.ACT_IMAGE_SELECT:
          fileName = util.null2string(data.getStringExtra(Constants.EXTRA_IMAGE_FILE_NAME));

          comHandler.sendMessageDelayed(comHandler.obtainMessage(
              MSG_COM_P_HOMEGRP_PROFILE_IMAGE), 10);
          break;
        default:
          break;
      }
    } else {
      switch (requestCode) {
        case Constants.ACT_HOMEMODE:
          if (data == null) {
            return;
          }
          Boolean isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
          if (isReload) {
            comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DASHBOARD), 10);
          }
          break;
        case Constants.ACT_NOTICE:
        case Constants.ACT_MESSAGE_CENTER:
          comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_G_DASHBOARD), 10);
          break;
        default:
          break;
      }
    }
  }
}
