package com.bozaixing.notes.fragments.account;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.CountDownTimer;
import android.support.annotation.StringRes;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bozaixing.common.app.PresenterFragment;
import com.bozaixing.common.util.ToastUtils;
import com.bozaixing.common.widgets.ClearTextIconEditText;
import com.bozaixing.factory.model.bean.User;
import com.bozaixing.factory.presenter.account.RegisterContratct;
import com.bozaixing.factory.presenter.account.RegisterPresenter;
import com.bozaixing.notes.R;
import com.bozaixing.notes.activities.MainActivity;

import net.qiujuer.genius.ui.compat.UiCompat;
import net.qiujuer.genius.ui.widget.Button;
import net.qiujuer.genius.ui.widget.Loading;

/**
 * Descr:   实现注册功能的碎片
 * Author:  bozaixing.
 * Email:   654152983@qq.com.
 * Date:    2017-09-21.
 */

public class RegisterFragment extends PresenterFragment<RegisterContratct.Presenter>
                                                    implements RegisterContratct.View,
                                                                    View.OnClickListener {


    /**
     * UI
     */
    private ImageView mCloseWindowView;

    private ClearTextIconEditText mPhoneTxt;
    private ClearTextIconEditText mSmsCodeTxt;
    private TextView mGetSmsCodeTxt;
    private ClearTextIconEditText mPasswordTxt;
    private ImageView mShowOrHidePasswordView;


    private FrameLayout mGoLoginLayout;

    private Button mRegisterSubmitBtn;
    private Loading mLoadingView;

    private AccountTrigger mAccountTrigger;



    private boolean mShowOrHidePasswordStatus = false;

    // 创建短信倒计时计数器的对象
    private SmsCodeCountDownTimer mSmsCodeCountDownTimer;



    @Override
    protected RegisterContratct.Presenter initPresenter() {
        return new RegisterPresenter(this);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        // 拿到当前Activity的引用
        mAccountTrigger = (AccountTrigger) context;


    }


    /**
     * 返回当前界面布局资源的ID
     *
     * @return
     */
    @Override
    protected int getLayoutResouceId() {
        return R.layout.fragment_register;
    }

    /**
     * 初始化界面显示控件
     *
     * @param rootView      根视图对象
     */
    @Override
    protected void initWidgets(View rootView) {
        super.initWidgets(rootView);
        // init UI
        mCloseWindowView = (ImageView) rootView.findViewById(R.id.register_close_window_view);

        mPhoneTxt = (ClearTextIconEditText) rootView.findViewById(R.id.register_phone_txt);
        mSmsCodeTxt = (ClearTextIconEditText) rootView.findViewById(R.id.register_sms_code_txt);
        mGetSmsCodeTxt = (TextView) rootView.findViewById(R.id.register_get_sms_code_txt);
        mPasswordTxt = (ClearTextIconEditText) rootView.findViewById(R.id.register_password_txt);
        mShowOrHidePasswordView = (ImageView) rootView.findViewById(R.id.register_show_or_hide_password_view);

        mGoLoginLayout = (FrameLayout) rootView.findViewById(R.id.register_go_login_layout);

        mRegisterSubmitBtn = (Button) rootView.findViewById(R.id.register_submit_btn);
        mLoadingView = (Loading) rootView.findViewById(R.id.register_loading_view);

    }


    /**
     * 当前界面显示控件注册监听事件
     */
    @Override
    protected void setListeners() {
        super.setListeners();

        // 关闭当前界面
        mCloseWindowView.setOnClickListener(this);

        // 为获取验证码的显示控件注册点击事件
        mGetSmsCodeTxt.setOnClickListener(this);

        // 为显示或者隐藏密码设置控件注册点击事件
        mShowOrHidePasswordView.setOnClickListener(this);


        // 跳转到登录碎片界面
        mGoLoginLayout.setOnClickListener(this);

        // 为提交按钮注册点击事件
        mRegisterSubmitBtn.setOnClickListener(this);

    }


    /**
     * 点击事件的处理方法
     *
     * @param v
     */
    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.register_close_window_view:       // 关闭当前界面
                if (getActivity() != null){
                    getActivity().finish();
                }
                break;
            case R.id.register_get_sms_code_txt:        // 获取短信验证码
                // 获取电话号码
                String mobile = mPhoneTxt.getText().toString();
                mPresenter.requestSmsCode(mobile);
                break;
            case R.id.register_show_or_hide_password_view:      // 显示或者隐藏密码
                // 密码显示状态取反
                mShowOrHidePasswordStatus = ! mShowOrHidePasswordStatus;

                if (mShowOrHidePasswordStatus){

                    // 用户可见的密码
                    mPasswordTxt.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    mShowOrHidePasswordView.setImageDrawable(
                            getResources().getDrawable(R.drawable.ic_vector_show_password));

                }else {
                    // 用户不可见的密码
                    mPasswordTxt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    mShowOrHidePasswordView.setImageDrawable(
                            getResources().getDrawable(R.drawable.ic_vector_hide_password));
                }


                break;
            case R.id.register_go_login_layout:
                // 跳转到登录碎片界面
                mAccountTrigger.triggerView();
                break;
            case R.id.register_submit_btn:
                // 获取用户界面的相关参数
                String phone = mPhoneTxt.getText().toString();
                String password = mPasswordTxt.getText().toString();
                String smsCode = mSmsCodeTxt.getText().toString();
                // 提交注册
                mPresenter.register(phone, password, smsCode);
                break;
        }

    }

    @Override
    public void showError(@StringRes int errRes) {
        super.showError(errRes);
        // 设置进度条停止
        mLoadingView.stop();

        // 设置让文本编辑控件可编辑
        mPhoneTxt.setEnabled(true);
        mPasswordTxt.setEnabled(true);

        // 设置注册提交按钮可点击
        mRegisterSubmitBtn.setEnabled(true);
    }


    @Override
    public void showLoading() {
        super.showLoading();

        if (mSmsCodeCountDownTimer != null){
            mSmsCodeCountDownTimer.onFinish();
        }

        // 加载注册进度条
        mLoadingView.start();

        // 设置让文本编辑控件不可编辑
        mPhoneTxt.setEnabled(false);
        mPasswordTxt.setEnabled(false);

        // 设置注册提交按钮不可继续点击
        mRegisterSubmitBtn.setEnabled(false);
    }


    /**
     * 发送短信成功V层的回调方法，用于实现倒计时功能
     */
    @Override
    public void requestSmsCodeSucceed(int strRes) {

        ToastUtils.show(mContext, strRes);

        // 初始化短信倒计时计算器
        mSmsCodeCountDownTimer = new SmsCodeCountDownTimer(60000, 1000);

        // 启动短信计时器
        mSmsCodeCountDownTimer.start();

    }

    /**
     * 注册成功的接口回掉方法
     */
    @Override
    public void registerSucceed(User user) {

        ToastUtils.show(getContext(), R.string.data_account_register_ok);

        // 注册成功切换到登录界面
        mAccountTrigger.triggerView();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        if (mSmsCodeCountDownTimer != null){
            mSmsCodeCountDownTimer.cancel();
        }
    }

    /**
     * 实现短信验证码倒计时功能
     */
    public class SmsCodeCountDownTimer extends CountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public SmsCodeCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {

            mGetSmsCodeTxt.setEnabled(false);
            mGetSmsCodeTxt.setText("重新发送(" + millisUntilFinished / 1000 + ")");
        }

        @Override
        public void onFinish() {

            mGetSmsCodeTxt.setEnabled(true);
            mGetSmsCodeTxt.setText(R.string.label_get_sms_code);
        }

    }



}
