/*
 * 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.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

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

  private static final int MSG_COM_P_MEMBER_INFO = 1;

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

  /*공통*/
  private Activity mActivity;
  private AppConfig mAppConfig;
  private Intent intent;
  private Util mUtil = new Util();
  private CustomDialog customDialog = new CustomDialog();
  @BindView(R.id.edtNickname) EditText mNickname;
  @BindView(R.id.llBtn1) LinearLayout mSave;

  @Override
  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

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

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

    ButterKnife.bind(this);

    setToolbar();
    setDisp();
  }

  /**
   * 툴바 셋팅.
   */
  private void setToolbar() {

    Toolbar toolbar = (Toolbar) mActivity.findViewById(R.id.toolbar);
    mUtil.setKeyboardHide(mActivity, toolbar);
    mUtil.getTextView(toolbar, R.id.tvToolbarTitle1).setVisibility(View.VISIBLE);
    mUtil.getTextView(toolbar, R.id.tvToolbarTitle2).setVisibility(View.GONE);
    mUtil.getTextView(toolbar, R.id.tvToolbarTitleDivider).setVisibility(View.GONE);
    mUtil.getTextView(toolbar, R.id.tvToolbarTitle3).setVisibility(View.GONE);
    mUtil.getTextView(toolbar, R.id.tvToolbarTitle4).setVisibility(View.GONE);
    mUtil.getTextView(toolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
    mUtil.getTextView(toolbar, R.id.btnToolbarMore).setVisibility(View.GONE);

    mUtil.getTextView(toolbar, R.id.tvToolbarTitle1)
            .setText(mUtil.getString(mActivity, R.string.layout_setting_nickname_change_01));
  }

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

    mNickname.setText(mAppConfig.getNickname());
    mNickname.setSelection(mAppConfig.getNickname().length());
  }

  @Override
  public void onConfigurationChanged(Configuration newConfig) {

    super.onConfigurationChanged(newConfig);
  }

  @OnClick({R.id.llBtn1, R.id.llBtn2})
  public void onClick(View view) {

    switch (view.getId()) {
      case R.id.llBtn1:
        mSave.setEnabled(false);
        comHandler.sendMessageDelayed(comHandler.obtainMessage(MSG_COM_P_MEMBER_INFO), Constants.HANDLER_DELAY_MILLIS);
        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_INFO:
          sendPutMemberInfo();
          break;
        default:
          break;
      }
      return true;
    }
  }

  /**
   * 회원 정보 수정(닉네임 정보에 대해 변경 처리한다) 요청.
   */
  private void sendPutMemberInfo() {

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

          resultPutMemberInfo(result);
        }
      });

      //공통 변수 입력
      httpSend.putChangeMemberInfo(Constants.KEY_NICKNAME, mNickname.getText().toString());
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

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

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

        mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG927), Toast.LENGTH_SHORT);
        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_RESULT_CODE));
        String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

        customDialog.msgAlert(mActivity, Constants.MSG000, errorMsg);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      customDialog.msgAlert(mActivity, Constants.MSG807);
    }
    try {
      mSave.setEnabled(true);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  @Override
  public void onBackPressed() {

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

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

    switch (msgId) {

      case Constants.MSG807:
        if (btnResult == 1) {
          comHandler.sendMessageDelayed(comHandler.obtainMessage(type), Constants.HANDLER_DELAY_MILLIS);
        }
        break;
      default:
        break;
    }
  }
}
