package com.yidianling.user.safePrivate

import android.app.KeyguardManager
import android.content.Context
import android.os.Build
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat
import android.support.v4.os.CancellationSignal
import com.ydl.ydlcommon.base.BaseApp
import com.yidianling.common.tools.LogUtil
import com.yidianling.user.UserHelper


/**
 * 指纹识别与手势管理器
 * Created by harvie on 2017/6/10 0010.
 */
class FingerPrintUtil {

    //存放解锁开关的文件


    var manager: FingerprintManagerCompat? = null
    var keyManager: KeyguardManager? = null

    var context: Context = BaseApp.getApp()

    private var mCancellationSignal: CancellationSignal? = null

    companion object {
        //后台到前台（10分钟内不需要验证）
//        val formBackgroundTime = 30*1000 //测试用
        val formBackgroundTime = 10 * 60 * 1000

        //指纹重试间隔时间
        val errorAgainTime: Long = 2 * 60 * 1000
        //指纹错误次数太多提示文案
        val errorMoreMessage: String = "错误次数太多，请稍后再试"
        //指纹错误提示文字
        val errorMessage: String = "请重试"
        //设置指纹多次错误的提示
        val errorTime: String = "指纹功能锁定，请2分钟后重试"
        //验证指纹或手势错误多次后提示
        val errorLogin: String = "\n错误次数太多,请验证账号\n"

        fun instance(): FingerPrintUtil {
            var fin: FingerPrintUtil = Inner.finger
            fin.init()
            return fin
        }

        //当前指纹识别是否可用
        fun getFingerPrintIsAviable(): Boolean {
            var time = System.currentTimeMillis()
            var errTime =UserHelper.getUsetSetting()?.fingerErrorTime?:0L
            var jiange : Long = time - errTime
            return jiange > FingerPrintUtil.errorAgainTime
        }
    }

    /** ********************************************指纹相关设置********************************************** */

    //设置指纹开关
    fun setFingerStatus(on: Boolean) {
        UserHelper.getUsetSetting()?.fingerPrintStatus = on
    }

    //app指纹是否开启
    fun fingerPrintIsOpen(): Boolean {
        return UserHelper.getUsetSetting()?.fingerPrintStatus?:false
    }

    private fun init() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (manager == null && keyManager == null) {
                manager = FingerprintManagerCompat.from(context)
                keyManager = context.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
            }
        }
    }

    //硬件设备是否支持指纹解锁功能
    fun isFingerPrintAvaliable(): Boolean? {
        return if (Build.VERSION.SDK_INT >= 23) {
            manager?.isHardwareDetected
        } else {
            false
        }
    }

    //判断是否有锁屏密码
    fun isLockHavePassword(): Boolean? {
        return keyManager?.isKeyguardSecure
    }


    //    判断设备是否录入指纹,貌似APP无法直接唤醒指纹设置页面
    fun isHaveFingerPrint(): Boolean? {
        return if (Build.VERSION.SDK_INT >= 23) {
            manager?.hasEnrolledFingerprints()
        } else {
            false
        }
    }


    //    开始识别指纹
//    参数分别是:防止第三方恶意攻击的包装类,CancellationSignal对象,flags,回调对象,handle
    fun startFingerPrint(call: FingerCallback) {
        if (Build.VERSION.SDK_INT >= 23) {
            if (mCancellationSignal == null) {
                mCancellationSignal = CancellationSignal()
            }
            manager?.authenticate(null, 0, mCancellationSignal, object : FingerprintManagerCompat.AuthenticationCallback() {
                override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
                    super.onAuthenticationError(errorCode, errString)
                    call.onAuthenticationError()
                    LogUtil.d("操作过于频繁")
                }

                override fun onAuthenticationSucceeded(result: FingerprintManagerCompat.AuthenticationResult?) {
                    super.onAuthenticationSucceeded(result)
                    call.onAuthenticationSucceeded()
                    LogUtil.d("指纹识别成功")
                }

                override fun onAuthenticationFailed() {
                    super.onAuthenticationFailed()
                    call.onAuthenticationFailed()
                    LogUtil.d("指纹识别失败")
                }
            }, null)
        }
    }

    //停止指纹监听
    fun cancelFingerListener() {
        if (Build.VERSION.SDK_INT >= 23) {
            mCancellationSignal?.cancel()
            mCancellationSignal = null
        }
    }

    private object Inner {
        val finger = FingerPrintUtil()
    }

    //指纹监听回调
    interface FingerCallback {
        fun onAuthenticationError()
        fun onAuthenticationSucceeded()
        fun onAuthenticationFailed()
    }

    /** *********************************************手势解锁相关方法********************************************** */

    //保存手势密码
    fun setHandPassword(password: String) {
        UserHelper.getUsetSetting()?.gesturePassword = password
    }

    //读取手势密码
    fun getHandPass(): String {
        return UserHelper.getUsetSetting()?.gesturePassword?:""
    }

    /************************************************其他与解锁相关的设置************************************************/

    //获取动态页面是否提示过安全解锁
    fun getTrendsSafeTip(): Boolean {
        return UserHelper.getUsetSetting()?.trendsIsClick?:true
    }

    //设置动态页面提示
    fun setTrendsSafeTip(status: Boolean) {
        UserHelper.getUsetSetting()?.trendsIsClick = status
    }

    //设置当前解锁成功时间
    fun setCurrentUnLockTime(time: Long) {
        UserHelper.getUsetSetting()?.unLockCheckSuccessTime = time
    }

    //是否设置指纹或手势密码
    fun appIsSetUnLockPass(): Boolean {
        return fingerPrintIsOpen() || !getHandPass().equals("")
    }

    //后台到前台是否需要解锁验证
    fun isShowActivity(): Boolean {
        //是否已设置解锁
        if (!fingerPrintIsOpen() && getHandPass().equals("")) {
            return false
        }
        var firstTime = UserHelper.getUsetSetting()?.unLockCheckSuccessTime?:System.currentTimeMillis()

        var curTime = System.currentTimeMillis()
        if (curTime - firstTime > formBackgroundTime) {
            //需要解锁验证
            return true
        }
        return false
    }

}