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

package com.ntels.onecable.view.invitation;

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

import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;

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

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

  private Activity act;
  Intent intent;
  private AppConfig appConfig;
  private Util util = new Util();
  private CustomDialog customDialog = new CustomDialog();
  private int type = 0;
  private static final int MSG_COM_P_HOMEGRP_MEMBERS_INVITATIONS = 1;
  private String homegrpId = "";
  private String imageFileName = "";
  private String authorizationQuestion = "";
  private String authorizationReply = "";
  private String errorCount = "";

  private boolean isReloadFinish = false;
  private boolean isBound = false;

  @Override
  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

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

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

    if (null != getIntent()) {
      Intent intent = getIntent();
      homegrpId = util.null2string(intent.getStringExtra(Constants.KEY_HOMEGRP_ID));
      authorizationQuestion = util.null2string(
          intent.getStringExtra(Constants.KEY_AUTHORIZATION_QUESTION));
      imageFileName = util.null2string(intent.getStringExtra(Constants.KEY_IMAGE_FILE_NAME));
    }

    displayListView();
  }

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

    util.getView(act, R.id.btnDate).setOnClickListener(this);
    util.getView(act, R.id.llBtn1).setOnClickListener(this);
    util.getTextView(act, R.id.tvTitle).setText(authorizationQuestion);
    util.setRefreshImage(act, imageFileName, R.id.ivMemberIcon);
  }

  @Override
  public void onClick(View view) {

    switch (view.getId()) {
      case R.id.llBtn1:
        onBackPressed();
        break;
      case R.id.btnDate:
        view.setEnabled(false);
        DialogDate dp1 = new DialogDate(act);
        dp1.setTitle(util.getString(act, R.string.layout_invitation_reply_02));
        dp1.setBtn1Val(util.getString(act, R.string.layout_ok));
        dp1.setBtn2Val(util.getString(act, R.string.layout_cancel));
        dp1.setMinDateVal("1900-01-01");
        dp1.setMaxDateVal("2100-12-31");
        dp1.setDtpVal(new DialogDate.DatePickerListner() {
          @Override
          public void onDoneButton(Dialog dialog, String date) {

            authorizationReply = date;
            dialog.dismiss();
            comHandler.sendMessageDelayed(comHandler.obtainMessage(
                MSG_COM_P_HOMEGRP_MEMBERS_INVITATIONS), 10);
          }

          @Override
          public void onCancelButton(Dialog dialog) {

            dialog.dismiss();
            try {
              util.getView(act, R.id.btnDate).setEnabled(true);
            } catch (Exception ex) {
              ex.printStackTrace();
            }
          }
        });
        dp1.init();
        dp1.show();
        break;
      default:
        break;
    }
  }

  @Override
  public void onConfigurationChanged(Configuration newConfig) {

    super.onConfigurationChanged(newConfig);
  }

  @Override
  public void onBackPressed() {

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

  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_P_HOMEGRP_MEMBERS_INVITATIONS:
          sendPostHomegrpMembersInvitations();
          break;
        default:
          break;
      }
      return true;
    }
  }

  /**
   * <pre>
   * 홈그룹 초대 알림(홈초대 알림 화면에서 승락/거절 처리를 한다) 요청.
   * (초대 수락 처리 후에 나머지 요청은 거절한다.)
   * </pre>
   */
  private void sendPostHomegrpMembersInvitations() {

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

          resultPostHomegrpMembersInvitations(result);
        }
      });
      String statusCode = "Y";
      httpSend.P_homegrp_members_invitations(homegrpId, statusCode, authorizationReply);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

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

    try {
      if (response.getStatusCode() == 200) {
        JSONObject joResult = new JSONObject(response.getContent());
        Dlog.v(joResult.toString());
        String homegrpId = "";
        if (joResult.has(Constants.KEY_HOMEGRP_ID)) {
          homegrpId = util.null2string(joResult.get(Constants.KEY_HOMEGRP_ID));
        }

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

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

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

        appConfig.setCtrtGroupId(homegrpId);
        appConfig.setSelect_Homegrp_Icon(homegrpImageFileName);
        appConfig.setSelect_Homegrp_Name(homegrpName);
        appConfig.setSelect_Homegrp_Grade_Code(gradeCode);

        errorCount = "";
        isReloadFinish = true;
        intent = new Intent();
        act.setResult(RESULT_OK, intent);
        finish();
      } else {
        JSONObject joResult = new JSONObject(response.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));
        String errorCount = util.null2string(joResult.get(Constants.KEY_ERROR_COUNT));

        switch (errorCode) {
          case "401":
            customDialog.msgAlert(act, Constants.MSG998, errorMsg);
            break;
          case "400-102":
            this.errorCount = errorCount;
            customDialog.msgAlert(act, Constants.MSG999, errorMsg);
            break;
          case "401-106":
            customDialog.msgAlert(act, Constants.MSG997, errorMsg);
            break;
          default:
            customDialog.msgAlert(act, Constants.MSG000, errorMsg);
            break;
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      customDialog.msgAlert(act, Constants.MSG807);
    }
    try {
      util.getView(act, R.id.btnDate).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.MSG999:
        if (btnResult == 1) {
          if (util.str2int(errorCount) < 3) {
            util.getView(act, R.id.btnDate).performClick();
          } else {
            isReloadFinish = true;
            onBackPressed();
          }
        }
        break;
      case Constants.MSG807:
        if (btnResult == 1) {
          comHandler.sendMessageDelayed(comHandler.obtainMessage(type), 10);
        }
        break;
      default:
        break;
    }
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    if (isBound) {
      isBound = false;
    }
  }
}
