/*
 * COPYRIGHT (c) 2018 All rights reserved by HANWHA LIFE.
 */
package kr.co.zumo.app.lifeplus.view.custom;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.StringRes;
import android.support.constraint.ConstraintLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
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;
import kr.co.zumo.app.lifeplus.view.dialog.IDialogResultListener;

/**
 * MobileAuthorizationView
 * <pre>
 * </pre>
 *
 * @author 민효동
 * @version 1.0
 * @history 민효동   [2018. 9. 28.]   [최초 작성]
 * @since 2018. 9. 28.
 */
public class MobileAuthorizationView extends ConstraintLayout implements View.OnClickListener, IMobileAuthorizationView {

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

  private LinearLayout scrollViewLinearLayout;
  private LinearLayout phoneIdentifyLayout;

  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;
  protected CheckBoxAllDriver checkBoxAllDriver;

  protected IDialogResultListener resultListener;

  public MobileAuthorizationView(Context context) {
    super(context);

    init(context);
  }

  public MobileAuthorizationView(Context context, AttributeSet attrs) {
    super(context, attrs);

    init(context);
  }

  public MobileAuthorizationView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    init(context);
  }

  public MobileAuthorizationView(Context context, IDialogResultListener resultListener) {
    super(context);
    this.resultListener = resultListener;

    init(context);
  }

  private void init(Context context) {
    inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inflater.inflate(R.layout.sign_up_phone_authorization_view, this);

    View view = this;

    scrollViewLinearLayout = view.findViewById(R.id.linear_layout_identify);
    phoneIdentifyLayout = view.findViewById(R.id.phone_identify_layout);
    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((compoundButton, b) -> presenter.setOnGenderCheckedChanged(b));

    // nationality
    radioSelectLocal.setOnCheckedChangeListener((compoundButton, 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(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) {
    resultListener.onDialogResult(null, event);
  }

  /**
   * dispose
   */
  public void dispose() {
    presenter.dispose();
  }
}
