//
//  PMFaceIDManger.swift
//  PhoneManager
//
//  Created by edy on 2025/5/15.
//

import UIKit
import LocalAuthentication


class PMFaceIDManger: NSObject {
   
    class func isAvailable() -> Bool {  // 有home键的全支持face id
        return cWindow?.safeAreaInsets.bottom ?? 0 > 0
    }
    
    class func request() -> Bool {
        if isAvailable() == false {
            return false
        }
        let context = LAContext()
        return context.biometricType == .faceID
    }
    
    class func authenticateWithFaceID(reason: String, completion: @escaping (Bool, Error?) -> Void) {
        let context = LAContext()
        context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { success, error in
            DispatchQueue.main.async {
                completion(success, error)
            }
        }
    }

}


extension LAContext {
    enum BiometricType {
        case none, touchID, faceID
    }

    var biometricType: BiometricType {
        var error: NSError?
        guard canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) else {
            self.handleLAError(error ?? NSError())
            return .none
        }
        if #available(iOS 11.0, *) {
            return biometryType == .faceID ? .faceID : .touchID
        }
        return .touchID
    }
    
    func handleLAError(_ error: Error) {
        if let laError = error as? LAError {
            switch laError.code {
            case .biometryNotAvailable:
                print("生物识别不可用：设备不支持或未启用")
                PMAlert(title: "Error" ,messsage: "App needs to access your face ID.",action: ["Yes","Open in Settings"]) { alert, idx in
                    if idx == 1 {
                        UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
                    }
                    alert.dismiss(animated: true)
                }
            case .biometryNotEnrolled:
                print("未录入生物特征")
                PMAlert(title:"Error" ,messsage: "There is no registered Face ID on your iPhone. You should register your Face ID first before using it." , action: ["OK"])
            case .biometryLockout:
                print("功能锁定，需输入设备密码")
                PMAlert(title:"Error" ,messsage: "FacelD cannot recognize your face. please try again later" , action: ["OK"])
            case .userCancel:
                print("用户取消验证")
            default:
                print("其他错误：\(laError.localizedDescription)")
            }
        }
    }
}
