package com.android.launcher3.settings;

import android.content.Context;

import com.secspace.lib.common.utils.Prefs;

public class ErrorTimeHelper {
    private static ErrorTimeHelper instance;
    private Context mContext;
    //错误次数
    private int mCount = 0;
    //锁定时间
    private int mMaxTime=10*1000*60;



    private ErrorTimeHelper(Context context) {
        mContext = context;
    }

    public static ErrorTimeHelper getInstance(Context context) {
        if (instance == null) {
            synchronized (ErrorTimeHelper.class) {
                if (instance == null) {
                    instance = new ErrorTimeHelper(context);
                }
            }
        }
        return instance;
    }

    /**
     * 设置错误次数  存放在Pres中，防止重启
     * @param count
     */
    public void setCount(int count) {
        this.mCount = count;
        if (mCount == 5) {
            setLockTime(System.currentTimeMillis());
        }
        Prefs.setLockCount(mContext, count);
    }

    public void addErrorCount() {
        this.mCount = getCount() + 1;
        if (mCount == 5) {
            setLockTime(System.currentTimeMillis());
        }
        Prefs.setLockCount(mContext, mCount);
    }

    public int getCount() {
        return Prefs.getLockCount(mContext);
    }

    public void setLockTime(long lockTime) {
        Prefs.setLockTime(mContext, lockTime);
    }

    public long getLockTime() {
        return Prefs.getLockTime(mContext);
    }

    /**
     * 判断时调用
     * @return
     */
    public boolean canShowDialog() {
        long lockTime = getLockTime();
        long nowTime = System.currentTimeMillis();
        if (nowTime - lockTime > mMaxTime) {
            if (getCount() == 5) {
                setCount(0);
            }
            return true;
        }
        return false;
    }

    /**
     * 输入错误时判断
     * @return
     */
    public boolean canInputPwd() {
        long lockTime = getLockTime();
        long nowTime = System.currentTimeMillis();
        if (nowTime - lockTime > mMaxTime) {
            if (getCount() >= 5) {
                setCount(0);
            }
            return true;
        }
        return false;
    }

    /**
     * 获取倒计时时间
     * @return
     */
    public int getCountDownTime() {
        long lockTime = getLockTime();
        long nowTime = System.currentTimeMillis();
        int alreadyLockTime = (int) (nowTime - lockTime);
        if (mMaxTime > alreadyLockTime) {
            return (mMaxTime - alreadyLockTime) / 1000;
        }
        return 0;
    }

    /**
     * 重置错误次数和锁定开始时间
     */
    public void resetLockTimeAndCount() {
        setCount(0);
        setLockTime(0L);
    }

}
