package kr.co.zumo.app.lifeplus.view.dialog;


import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.DialogFragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import kr.co.zumo.app.R;
import kr.co.zumo.app.lifeplus.util.ResourceUtil;
import kr.co.zumo.app.lifeplus.view.CheckBoxAllDriver;
import kr.co.zumo.app.lifeplus.view.Event;

/**
 * MobileAuthorizationDialog
 * <pre>
 *   휴대폰 본인인증 화면 dialog 구현
 * </pre>
 *
 * @author 하세미
 * @version 1.0
 * @history 하세미   [2018-09-14]   [최초 작성]
 * @since 2018-09-14
 */
public class MobileAuthorizationDialog extends DialogBase implements View.OnClickListener, IMobileAuthorizationDialog {

  private Button buttonConfirm;
  private Button buttonTimeExpansion;
  private Button buttonIdentifyNumberSend;

  private LinearLayout scrollViewLinearLayout;
  private LinearLayout phoneIdentifyLayout;
  private ScrollView scrollView;

  private EditText editTextName;
  private RadioButton radioSelectLocal;
  private RadioButton radioSelectForeigner;
  private EditText editTextBirthDate;
  private RadioButton radioSelectMale;
  private RadioButton radioSelectFemale;
  private CheckBox checkBoxAllAgree;
  private Spinner spinnerMobileCompany;
  private Spinner spinnerFirstPhoneNumber;
  private EditText editTextPhoneNumber;
  private EditText editTextAuthorizedNumber;
  private TextView textViewPhoneIdentifyTime;
  private InputMethodManager inputMethodManager;
  private TextView textViewBirthValidation;
  private TextView textViewNameValidation;
  private TextView textViewPhoneValidation;
  private TextView textAuthorizedNumberValidation;

  private MobileAuthorizationPresenter presenter;
  CheckBoxAllDriver checkBoxAllDriver;


  public MobileAuthorizationDialog() {
    super();
  }

  /**
   * 전체적인 customDialog 스타일 지정
   *
   * @param savedInstanceState
   */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    setStyle(DialogFragment.STYLE_NORMAL, R.style.CustomDialog);
    inputMethodManager = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);

    super.onCreate(savedInstanceState);
  }

  @Override
  public void onDismiss(DialogInterface dialog) {
    super.onDismiss(dialog);
    Log.i("APP# MobileAuthorizationDialog | onDismiss", "|");
    presenter.dispose();
  }

  @Override
  public void onCancel(DialogInterface dialog) {
    Log.i("APP# MobileAuthorizationDialog | onCancel", "|" + dialog);
  }

  @Override
  public void setResultListener(IDialogResultListener resultListener) {
    super.setResultListener(resultListener);
  }

  @Override
  public void setEnabled() {

  }

  @Override
  public void setDisabled() {

  }

  @Override
  public void restart() {

  }

  /**
   * CustomDialog view 화면 리턴, 상단바 타이틀 제목을 설정하여 띄운다.
   *
   * @param inflater
   * @param container
   * @param savedInstanceState
   * @return
   */
  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    getDialog().setTitle(R.string.sign_up_mobile_identify_pop_up);
    addButtonToDialogTitle(getDialog());

    View view = inflater.inflate(R.layout.sign_up_phone_identify_dialog, container, false);
    initView(view);

    return view;
  }

  /**
   * 레이아웃 크기 지정
   */
  @Override
  public void onStart() {
    super.onStart();
  }

  /**
   * 상단 바의 닫힘 버튼 구현 및 버튼 클릭 이벤트 발생
   *
   * @param dialog
   */
  private void addButtonToDialogTitle(final Dialog dialog) {
    final TextView title = (TextView) dialog.findViewById(android.R.id.title);
    title.setCompoundDrawablesWithIntrinsicBounds(0, 0, android.R.drawable.ic_delete, 0);
    title.setOnClickListener(view -> {
      getResultListener().onDialogCanceled(MobileAuthorizationDialog.this);
    });
  }

  /**
   * view item setting
   *
   * @param view
   */
  private void initView(View view) {
    scrollViewLinearLayout = view.findViewById(R.id.linear_layout_identify);
    phoneIdentifyLayout = view.findViewById(R.id.phone_identify_layout);
    scrollView = view.findViewById(R.id.scroll_view_identify);
    buttonConfirm = view.findViewById(R.id.button_phone_identify_confirm);
    buttonTimeExpansion = view.findViewById(R.id.button_phone_identify_time_expansion);
    buttonIdentifyNumberSend = view.findViewById(R.id.button_identify_number_send);

    editTextName = view.findViewById(R.id.edit_text_name);
    radioSelectLocal = view.findViewById(R.id.radio_button_local);
    radioSelectForeigner = view.findViewById(R.id.radio_button_foreign);
    editTextBirthDate = view.findViewById(R.id.edit_text_birth_date);
    radioSelectMale = view.findViewById(R.id.radio_button_male);
    radioSelectFemale = view.findViewById(R.id.radio_button_female);
    checkBoxAllAgree = view.findViewById(R.id.checkbox_all_agree);
    spinnerMobileCompany = view.findViewById(R.id.spinner_mobile_company);
    spinnerFirstPhoneNumber = view.findViewById(R.id.spinner_first_phone_number);
    editTextPhoneNumber = view.findViewById(R.id.edit_text_phone_number);
    editTextAuthorizedNumber = view.findViewById(R.id.edit_text_authorized_number);
    textViewPhoneIdentifyTime = view.findViewById(R.id.text_view_phone_identify_time);
    textViewBirthValidation = view.findViewById(R.id.text_view_birth_validation);
    textViewNameValidation = view.findViewById(R.id.text_view_name_validation);
    textViewPhoneValidation = view.findViewById(R.id.text_view_phone_number_validation);
    textAuthorizedNumberValidation = view.findViewById(R.id.text_authorized_number_validation);

    presenter = new MobileAuthorizationPresenter(this);

    scrollViewLinearLayout.setOnClickListener(this);
    buttonConfirm.setOnClickListener(this);
    buttonTimeExpansion.setOnClickListener(this);
    buttonIdentifyNumberSend.setOnClickListener(this);

    checkBoxAllDriver = new CheckBoxAllDriver(checkBoxAllAgree);

    // 전체 약관 동의
    checkBoxAllAgree.setOnClickListener(v12 -> {
      boolean b = checkBoxAllAgree.isChecked();
      checkBoxAllDriver.applyCheckAll(b);
      presenter.onAllAgreeCheckedChanged(b);
    });

    // 약관 동의
    int len = 4;
    CheckBox checkBox;
    View v;
    for (int i = 0; i < len; ++i) {
      int index = i;

      checkBox = view.findViewById(ResourceUtil.getId("checkbox_agree" + (i + 1)));
      checkBoxAllDriver.addChildBox(checkBox);
      checkBox.setOnCheckedChangeListener((compoundButton, b) -> {
        checkBoxAllDriver.check();
        presenter.onAgreeCheckedChanged(index, b);
      });

      v = view.findViewById(ResourceUtil.getId("button_identify_agree" + (i + 1)));
      v.setOnClickListener(v1 -> {
        presenter.onClickAgreeDetail(index);
      });
    }

    // name
    editTextName.setOnFocusChangeListener((view1, isFocusChanged) -> {
      presenter.onFocusNameText(isFocusChanged);
    });
    editTextName.addTextChangedListener(new TextWatcher() {
      @Override
      public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

      @Override
      public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        presenter.onNameTextChanged(charSequence.toString());
      }

      @Override
      public void afterTextChanged(Editable editable) {}
    });

    // birthDate
    editTextBirthDate.setOnFocusChangeListener((view12, isFocusChanged) -> {
      presenter.onFocusBirthDateText(isFocusChanged);
    });
    editTextBirthDate.addTextChangedListener(new TextWatcher() {
      @Override
      public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

      @Override
      public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        presenter.onBirthDateTextChanged(charSequence.toString());
      }

      @Override
      public void afterTextChanged(Editable editable) {}
    });

    // phone number
    editTextPhoneNumber.setOnFocusChangeListener((view1, isFocusChanged) -> {
      presenter.onFocusPhoneNumberText(isFocusChanged);
    });
    editTextPhoneNumber.addTextChangedListener(new TextWatcher() {
      @Override
      public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

      @Override
      public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        presenter.onPhoneNumberTextChanged(charSequence.toString());
      }

      @Override
      public void afterTextChanged(Editable editable) {}
    });

    // 인증 번호
    editTextAuthorizedNumber.setOnFocusChangeListener((view1, isFocusChanged) -> {
      presenter.onFocusValidationNumberText(isFocusChanged);
    });
    editTextAuthorizedNumber.addTextChangedListener(new TextWatcher() {
      @Override
      public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

      @Override
      public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        presenter.onAuthorizedNumberChanged(charSequence.toString());
      }

      @Override
      public void afterTextChanged(Editable editable) {}
    });

    // gender
    radioSelectMale.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override
      public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        presenter.setOnGenderCheckedChanged(b);
      }
    });

    // nationality
    radioSelectLocal.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override
      public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        presenter.onNationalCheckedChanged(b);
      }
    });

    // 폰 국번
    spinnerFirstPhoneNumber.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
      @Override
      public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        presenter.onFirstPhoneNumberSelectChanged(adapterView.getSelectedItem().toString());
      }

      @Override
      public void onNothingSelected(AdapterView<?> adapterView) {}
    });
    spinnerFirstPhoneNumber.setOnTouchListener(new View.OnTouchListener() {
      @Override
      public boolean onTouch(View view, MotionEvent motionEvent) {
        presenter.onClickSpinner();
        return false;
      }
    });

    // 폰 회사
    spinnerMobileCompany.setOnTouchListener(new View.OnTouchListener() {
      @Override
      public boolean onTouch(View view, MotionEvent motionEvent) {
        presenter.onClickSpinner();
        return false;
      }
    });
    spinnerMobileCompany.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
      @Override
      public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        presenter.onFirstMobileCompanySelectChanged(adapterView.getSelectedItem().toString());
      }

      @Override
      public void onNothingSelected(AdapterView<?> adapterView) {}
    });

  }

  @Override
  public void onClick(View view) {
    switch (view.getId()) {
      case R.id.button_phone_identify_confirm:
        presenter.onAuthorizationConfirmButtonClick();
        break;
      case R.id.button_phone_identify_time_expansion:
        presenter.onAuthorizationTimeExpansionButtonClick();
        break;
      case R.id.button_identify_number_send:
        presenter.onAuthorizationNumberSendButtonClick();
        break;
      case R.id.linear_layout_identify:
        presenter.onClickLayout();
        break;
      default:
        break;
    }
  }

  @Override
  public void setEnabledRequestConfirmButton(boolean isEnabled) {
    buttonConfirm.setEnabled(isEnabled);
  }

  @Override
  public void setEnabledRequestConfirmTextView(boolean isEnabled) {
    editTextAuthorizedNumber.setEnabled(isEnabled);
  }

  @Override
  public void doClearRequestConfirmTextView() {
    editTextAuthorizedNumber.setText("");
  }

  @Override
  public void setEnabledRequestNumberButton(boolean isEnabled) {
    buttonIdentifyNumberSend.setEnabled(isEnabled);
  }

  @Override
  public void renderRetryButton(String str) {
    buttonIdentifyNumberSend.setText(str);
  }

  @Override
  public void doHideKeyBoard() {
    inputMethodManager.hideSoftInputFromWindow(getView().getWindowToken(), 0);
  }

  @Override
  public void doClearNameValidationTextView() {
    textViewNameValidation.setText("");
  }

  @Override
  public void doNameValidationMessage(@StringRes int StringId) {
    textViewNameValidation.setText(StringId);
  }

  @Override
  public void doClearBirthDateValidationTextView() {
    textViewBirthValidation.setText("");
  }

  @Override
  public void doBirthDateValidationMessage(@StringRes int stringId) {
    textViewBirthValidation.setText(stringId);
  }

  @Override
  public void doClearPhoneNumberValidationTextView() {
    textViewPhoneValidation.setText("");
  }

  @Override
  public void doPhoneNumberCheckedValidationMessage(@StringRes int stringId) {
    textViewPhoneValidation.setText(stringId);
  }

  @Override
  public void doAuthorizedNumberValidationMessage(@StringRes int stringId) {
    textAuthorizedNumberValidation.setText(stringId);
  }

  @Override
  public void doClearAuthorizedNumberValidationTextView() {
    textAuthorizedNumberValidation.setText("");
  }

  @Override
  public void showRemainTime(boolean isVisible) {
    phoneIdentifyLayout.setVisibility(isVisible ? View.VISIBLE : View.GONE);
  }

  @Override
  public void setEnabledExpansionTimeButton(boolean isEnabled) {
    buttonTimeExpansion.setEnabled(isEnabled);
  }

  @Override
  public void renderRemainTime(String time) {
    textViewPhoneIdentifyTime.setText(time);
  }

  @Override
  public void onResultDelegate(Event event) {
    if(null != resultListener) {
      resultListener.onDialogResult(this, event);
    }
  }
}
