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

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.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
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.custom.CustomSpinner;

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

  private View buttonConfirm;
  private TextView buttonTimeExpansion;
  private TextView buttonIdentifyNumberSend;

  private LinearLayout scrollViewLinearLayout;
  private LinearLayout phoneIdentifyLayout;
  private LinearLayout agreeListLayout;

  private EditText editTextName;
  private RadioButton radioSelectLocal;
  private EditText editTextBirthDate;
  private RadioButton radioSelectMale;
  private CheckBox checkBoxAllAgree;
  private CustomSpinner spinnerMobileCompany;
  private CustomSpinner 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 LinearLayout buttonAllAgreeDetail;
  private ImageView imageViewArrow;
  private RelativeLayout layoutInputAuthNumber;

  private View viewNameBar;
  private View viewBirthDateBar;
  private View viewPhoneNumberBar;
  private View viewAuthNumberBar;
  private View viewCompanyBar;
  private View viewFirstNumberBar;
  private View viewAgreeBar;

  private IMobileAuthContract.Presenter presenter;
  protected CheckBoxAllDriver checkBoxAllDriver;

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

    init(context);
  }

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

    init(context);
  }

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

    init(context);
  }

  @Override
  public void setPresenter(IMobileAuthContract.Presenter presenter) {
    this.presenter = presenter;
  }

  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_auth_view, this);

    scrollViewLinearLayout = findViewById(R.id.linear_layout_identify);
    phoneIdentifyLayout = findViewById(R.id.phone_identify_layout);
    agreeListLayout = findViewById(R.id.layout_agree_list);
    buttonConfirm = findViewById(R.id.button_phone_identify_confirm);
    buttonTimeExpansion = findViewById(R.id.button_phone_identify_time_expansion);
    buttonIdentifyNumberSend = findViewById(R.id.button_identify_number_send);

    editTextName = findViewById(R.id.edit_text_name);
    radioSelectLocal = findViewById(R.id.radio_button_local);
    editTextBirthDate = findViewById(R.id.edit_text_birth_date);
    radioSelectMale = findViewById(R.id.radio_button_male);
    checkBoxAllAgree = findViewById(R.id.checkbox_all_agree);
    spinnerMobileCompany = findViewById(R.id.spinner_mobile_company);
    spinnerFirstPhoneNumber = findViewById(R.id.spinner_first_phone_number);
    editTextPhoneNumber = findViewById(R.id.edit_text_phone_number);
    editTextAuthorizedNumber = findViewById(R.id.edit_text_authorized_number);
    textViewPhoneIdentifyTime = findViewById(R.id.text_view_phone_identify_time);
    textViewBirthValidation = findViewById(R.id.text_view_birth_validation);
    textViewNameValidation = findViewById(R.id.text_view_name_validation);
    textViewPhoneValidation = findViewById(R.id.text_view_phone_number_validation);
    textAuthorizedNumberValidation = findViewById(R.id.text_authorized_number_validation);
    buttonAllAgreeDetail = findViewById(R.id.button_all_agree_detail);
    imageViewArrow = findViewById(R.id.image_view_arrow);
    layoutInputAuthNumber = findViewById(R.id.layout_input_auth_number);

    viewNameBar = findViewById(R.id.edit_text_name_bar);
    viewBirthDateBar = findViewById(R.id.edit_text_birth_date_bar);
    viewPhoneNumberBar = findViewById(R.id.edit_text_phone_number_bar);
    viewAuthNumberBar = findViewById(R.id.edit_text_authorized_number_bar);
    viewCompanyBar = findViewById(R.id.spinner_mobile_company_bar);
    viewFirstNumberBar = findViewById(R.id.spinner_first_phone_number_bar);
    viewAgreeBar = findViewById(R.id.checkbox_all_agree_bar);

    checkBoxAllDriver = new CheckBoxAllDriver(checkBoxAllAgree);

    // 전체 약관 동의
    checkBoxAllAgree.setOnClickListener(v12 -> {
      boolean b = checkBoxAllAgree.isChecked();
      checkBoxAllDriver.applyCheckAll(b);
      presenter.onAllAgreeCheckedChanged(b);
    });
//    checkBoxAllAgree.setTypeface(ResourcesCompat.getFont(context, R.font.font1));

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

      checkBox = findViewById(ResourceUtil.getId("checkbox_agree" + (i + 1)));
      checkBoxAllDriver.addChildBox(checkBox);
      checkBox.setOnCheckedChangeListener((compoundButton, b) -> {
        checkBoxAllDriver.check();
        presenter.onAgreeCheckedChanged(index, b);
      });
//      checkBox.setTypeface(ResourcesCompat.getFont(context, R.font.font1));

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

    // name
    editTextName.setOnFocusChangeListener((view1, hasFocus) -> {
      presenter.onFocusNameText(hasFocus);
      setBarBackgroundColor(viewNameBar, hasFocus);
    });
    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, hasFocus) -> {
      presenter.onFocusBirthDateText(hasFocus);
      setBarBackgroundColor(viewBirthDateBar, hasFocus);
    });
    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, hasFocus) -> {
      presenter.onFocusPhoneNumberText(hasFocus);
      setBarBackgroundColor(viewPhoneNumberBar, hasFocus);
    });
    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, hasFocus) -> {
      presenter.onFocusValidationNumberText(hasFocus);
      setBarBackgroundColor(viewAuthNumberBar, hasFocus);
    });
    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.setSpinnerEventsListener(new CustomSpinner.OnSpinnerEventsListener() {
      @Override
      public void onSpinnerOpened(Spinner spin) {
        presenter.onFirstPhoneNumberOpenChanged(true);
        setBarBackgroundColor(viewFirstNumberBar, true);
      }

      @Override
      public void onSpinnerClosed(Spinner spin) {
        presenter.onFirstPhoneNumberOpenChanged(false);
        setBarBackgroundColor(viewFirstNumberBar, false);
      }
    });
    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) {}
    });

    // 폰 회사
    spinnerMobileCompany.setSpinnerEventsListener(new CustomSpinner.OnSpinnerEventsListener() {
      @Override
      public void onSpinnerOpened(Spinner spin) {
        presenter.onFirstMobileCompanyOpenChanged(true);
        setBarBackgroundColor(viewCompanyBar, true);
      }

      @Override
      public void onSpinnerClosed(Spinner spin) {
        presenter.onFirstMobileCompanyOpenChanged(false);
        setBarBackgroundColor(viewCompanyBar, 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) {
      }
    });


    // layout
    scrollViewLinearLayout.setOnFocusChangeListener((v, hasFocus) -> {
      if (hasFocus) {
        /**
         *  edit text 들의 포커스를 없애기 위해서 layout 에 포커스를 주면 키보드가 나오므로 숨겨줌
         */
        doHideKeyBoard();
      }
    });
    scrollViewLinearLayout.setOnClickListener(v -> presenter.onClickLayout());

    buttonConfirm.setOnClickListener(v -> presenter.onAuthorizationConfirmButtonClick());
    buttonTimeExpansion.setOnClickListener(v -> presenter.onAuthorizationTimeExpansionButtonClick());
    buttonIdentifyNumberSend.setOnClickListener(v -> presenter.onAuthorizationNumberSendButtonClick());
    buttonAllAgreeDetail.setOnClickListener(v -> presenter.doAccordionAgreeList(agreeListLayout.getVisibility() == View.VISIBLE));
  }

  private void setBarBackgroundColor(View view, boolean hasFocus) {
    view.setBackgroundColor(hasFocus ? ResourceUtil.getColor(R.color.C000000) : ResourceUtil.getColor(R.color.CE5E5E5));
  }

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

  @Override
  public void setEnabledRequestConfirmTextView(boolean isEnabled) {
    editTextAuthorizedNumber.setEnabled(isEnabled);
    layoutInputAuthNumber.setVisibility(isEnabled ? View.VISIBLE : View.GONE);
  }

  @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 doAccordionAgreeList(boolean isVisible) {
    if (isVisible) {
      imageViewArrow.setImageResource(R.drawable.icon_openarrow);
      agreeListLayout.setVisibility(GONE);
      setBarBackgroundColor(viewAgreeBar, false);
    }
    else {
      imageViewArrow.setImageResource(R.drawable.icon_closearrow);
      agreeListLayout.setVisibility(VISIBLE);
      setBarBackgroundColor(viewAgreeBar, true);
    }

  }

  /**
   * 모든 UI disabled
   */
  public void setDisabledAll() {
    scrollViewLinearLayout.setEnabled(false);
    setEnabledWithChildren(scrollViewLinearLayout, false);
  }

  private void setEnabledWithChildren(ViewGroup vg, boolean enable) {
    for (int i = 0; i < vg.getChildCount(); i++) {
      View child = vg.getChildAt(i);
      child.setEnabled(enable);
      if (child instanceof ViewGroup) {
        setEnabledWithChildren((ViewGroup) child, enable);
      }
    }
  }

  /**
   * 모든 포커스 제거;
   */
  @Override
  public void clearFocusAll() {
    /**
     * 모든 UI 에 포커스를 제거하는 대신 layout 에 포커스를 넘긴다.
     * 단, 키보드가 나오므로 이는 포커스 이벤트를 받아서 숨겨줘야한다.
     */
    scrollViewLinearLayout.requestFocus();
  }

  /**
   * dispose
   */
  public void dispose() {
  }
}
