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

package com.ntels.onecable.view.mainmore;

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 org.json.JSONObject;

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.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

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

  private static final int MSG_COM_P_MEMBER_MEMBER_ID_UPDATE_FIELD = 1;

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

  /*공통*/
  private Activity act;
  private AppConfig appConfig;
  private Intent intent;
  private Util util = new Util();
  private CustomDialog customDialog = new CustomDialog();
  private String updateField = "";
  private String newEmailId = "";
  private String oldPassword = "";
  private String newPassword = "";
  private String confirmPassword = "";
  private String nickname = "";
  private String imageFileName = "";

  @Override
  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

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

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

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

    updateField = "name";
    setDisp();
  }

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

    util.getTextView(act, R.id.edtName).setText(appConfig.getNickname());
  }

  @Override
  public void onConfigurationChanged(Configuration newConfig) {

    super.onConfigurationChanged(newConfig);
  }

  @Override
  public void onClick(View view) {

    switch (view.getId()) {
      case R.id.llBtn1:
        nickname = util.getEditTextVal(act, R.id.edtName);
        if (nickname.equals("")) {
          util.setShowToast(act, util.getString(act, R.string.layout_join_02)
              + util.getString(act, R.string.MSG902), Toast.LENGTH_SHORT);
          return;
        }
        view.setEnabled(false);
        comHandler.sendMessageDelayed(comHandler.obtainMessage(
            MSG_COM_P_MEMBER_MEMBER_ID_UPDATE_FIELD), 10);
        break;
      case R.id.llBtn2:
        onBackPressed();
        break;
      default:
        break;
    }
  }

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

  /**
   * 회원 정보 수정(가입된 이메일, 비밀번호, 이름 정보에 대해 변경 처리한다) 요청.
   */
  private void sendPutMemberInfoUpdate() {

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

          resultPutMemberInfoUpdate(result);
        }
      });

      //공통 변수 입력
      httpSend.P_member_member_id_update_field(appConfig.getLogin_Member_Id(),
          updateField, newEmailId, oldPassword, newPassword, confirmPassword,
          nickname, imageFileName);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

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

    try {
      if (response.getStatusCode() == 200) {

        util.setShowToast(act, util.getString(act, R.string.MSG843), Toast.LENGTH_SHORT);
        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));

        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.llBtn1).setEnabled(true);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  @Override
  public void onBackPressed() {

    intent = new Intent();
    act.setResult(RESULT_CANCELED, intent);
    finish();
  }

  @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);
        }
        break;
      default:
        break;
    }
  }
}
