/*
 * 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 mActivity;
  Intent intent;
  private AppConfig mAppConfig;
  private Util mUtil = 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);

    mActivity = InvitationReply.this;
    mAppConfig = (AppConfig) mActivity.getApplicationContext();
    customDialog.setOnMsgAlterToResultEvent(this);

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

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

    displayListView();
  }

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

    mUtil.getView(mActivity, R.id.btnDate).setOnClickListener(this);
    mUtil.getView(mActivity, R.id.llBtn1).setOnClickListener(this);
    mUtil.getTextView(mActivity, R.id.tvTitle).setText(authorizationQuestion);
    mUtil.setRefreshImage(mActivity, 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(mActivity);
        dp1.setTitle(mUtil.getString(mActivity, R.string.layout_invitation_reply_02));
        dp1.setBtn1Val(mUtil.getString(mActivity, R.string.layout_ok));
        dp1.setBtn2Val(mUtil.getString(mActivity, 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();
            mComHandler.sendMessageDelayed(mComHandler.obtainMessage(
                MSG_COM_P_HOMEGRP_MEMBERS_INVITATIONS), 10);
          }

          @Override
          public void onCancelButton(Dialog dialog) {

            dialog.dismiss();
            try {
              mUtil.getView(mActivity, 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);
    mActivity.setResult(RESULT_CANCELED, intent);
    finish();
  }

  Handler mComHandler = 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(mActivity);
      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 = mUtil.null2string(joResult.get(Constants.KEY_HOMEGRP_ID));
        }

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

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

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

        mAppConfig.setCtrtGroupId(homegrpId);
//        mAppConfig.setSelect_Homegrp_Icon(homegrpImageFileName);
        mAppConfig.setCtrtGroupName(homegrpName);
        mAppConfig.setCtrtGroupGradeCode(gradeCode);

        errorCount = "";
        isReloadFinish = true;
        intent = new Intent();
        mActivity.setResult(RESULT_OK, intent);
        finish();
      } 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));
        String errorCount = mUtil.null2string(joResult.get(Constants.KEY_ERROR_COUNT));

        switch (resultCode) {
          case "401":
            customDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
            break;
          case "400-102":
            this.errorCount = errorCount;
            customDialog.msgAlert(mActivity, Constants.MSG999, resultMsg);
            break;
          case "401-106":
            customDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
            break;
          default:
            customDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
            break;
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      customDialog.msgAlert(mActivity, Constants.MSG807);
    }
    try {
      mUtil.getView(mActivity, R.id.btnDate).setEnabled(true);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  @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.MSG999:
        if (btnResult == 1) {
          if (mUtil.str2int(errorCount) < 3) {
            mUtil.getView(mActivity, R.id.btnDate).performClick();
          } else {
            isReloadFinish = true;
            onBackPressed();
          }
        }
        break;
      case Constants.MSG807:
        if (btnResult == 1) {
          mComHandler.sendMessageDelayed(mComHandler.obtainMessage(type), 10);
        }
        break;
      default:
        break;
    }
  }

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