package com.sunzee.mvp.login;

import android.text.TextUtils;

import com.sunzee.base.BasePresenter;
import com.sunzee.model.domain.Name;
import com.sunzee.utils.SharedPreferencesUtils;

/**
 * 登录界面 presenter
 */
public class LoginPresenter extends BasePresenter<LoginView> {


    private int inputErrorTime;
    private boolean isThreadStart;
    private int countdownTime = 20;

    public LoginPresenter(LoginView view) {
        attachView(view);
        String admin = (String) SharedPreferencesUtils.getParam(Name.ADMIN, "-1");
        String guest = (String) SharedPreferencesUtils.getParam(Name.GUEST, "-1");
        if (admin == null || admin.equals("-1")) {
            //本地没有密码
            SharedPreferencesUtils.setParam(Name.ADMIN, "123456");
        }

        if (guest == null || guest.equals("-1")) {
            //本地没有密码
            SharedPreferencesUtils.setParam(Name.GUEST, "123456");
        }
    }

    public void login(String userName, String password) {
        //是否输入为空
        if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(password)) {
            mvpView.inputEmpty();
            return;
        }
        //是否输入两次错误
        if (inputErrorTime == 2) {
            if (!isThreadStart) {
                new Thread(new CountDownThread()).start();
            }
            mvpView.laterInput(countdownTime);
            return;
        }

        String admin = (String) SharedPreferencesUtils.getParam(Name.ADMIN, "-1");
        String guest = (String) SharedPreferencesUtils.getParam(Name.GUEST, "-1");
        if (userName.equals(Name.ADMIN) && password.equals(admin)) {
            SharedPreferencesUtils.setParam(Name.ACCOUNT_STATE, 0);
            mvpView.loginSuccessful();
        } else if (userName.equals(Name.GUEST) && password.equals(guest)) {
            SharedPreferencesUtils.setParam(Name.ACCOUNT_STATE,1);
            mvpView.loginSuccessful();
        } else {
            mvpView.loginUserFailed();
            inputErrorTime++;
        }
    }


    //输错两次后等待20s再尝试
    class CountDownThread extends Thread {
        @Override
        public void run() {
            isThreadStart = true;
            try {
                while (countdownTime >= 0) {
                    Thread.sleep(1000);
                    countdownTime--;
                }
                isThreadStart = false;
                countdownTime = 20;
                inputErrorTime = 0;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
