//
//  UIDevice+Ext.swift
//  LegendTeam
//
//  Created by lym on 2022/2/16.
//

import Foundation
import UIKit
import UICKeyChainStore

extension UIDevice {
    static var UUID: String {
        let service = Bundle.appBundleID + ".uuid"
        let key = Bundle.appBundleID + ".uuid" + ".key"
        let keychain = UICKeyChainStore(service: service)
        if let uuid = keychain.string(forKey: key) {
            return uuid
        }
        // 8-4-4-4-12
        // F9C5E3F8-2396-435E-AD11-02446C943FB2
        var uuid2 = UIDevice.current.identifierForVendor?.uuidString
        if uuid2 == nil {
            let timeInterval = Int(Date().timeIntervalSince1970)
            uuid2 = String.randomString(8)
            + "-" + String.randomString(4)
            + "-" + String.randomString(4)
            + "-" + String.randomString(4)
            + "-" + "\(timeInterval)" + String.randomString(2)
        }
        keychain.setString(uuid2, forKey: key)
        return uuid2!
    }
    
    var isPhone: Bool {
        return userInterfaceIdiom == .phone
    }

    var isPad: Bool {
        return userInterfaceIdiom == .pad
    }

    var isSimulator: Bool {
        #if targetEnvironment(simulator)
            return true
        #else
            return false
        #endif
    }

    var hasNotch: Bool {
        if #available(iOS 13.0, *) {
            // Use UIWindowScene.windows for iOS 15 and later
            let windowScene = UIApplication.shared.connectedScenes
                .compactMap { $0 as? UIWindowScene }
                .first
            return windowScene?.windows.first?.safeAreaInsets.bottom ?? 0 > 0
        } else {
            // Fallback for iOS versions before 15.0
            return UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 0 > 0
        }
    }
    
    var safeBottom: CGFloat {
        if #available(iOS 13.0, *) {
            // Use UIWindowScene.windows for iOS 15 and later
            let windowScene = UIApplication.shared.connectedScenes
                .compactMap { $0 as? UIWindowScene }
                .first
            return windowScene?.windows.first?.safeAreaInsets.bottom ?? 0.0
        } else {
            // Fallback for iOS versions before 15.0
            return UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 0.0
        }
    }
    
    // 状态栏 高度
    var statusBarHeight: CGFloat {
        if #available(iOS 13.0, *) {
            let windowScene = UIApplication.shared.connectedScenes
                .compactMap { $0 as? UIWindowScene }
                .first
            return windowScene?.statusBarManager?.statusBarFrame.size.height ?? 0
        } else {
            return UIApplication.shared.statusBarFrame.size.height
        }
    }
    
    // 导航栏 高度
    var navBarHeight: CGFloat {
        return UINavigationController().navigationBar.frame.height
    }
    
    // 状态栏 + 导航栏 高度
    var navHeight: CGFloat {
        return navBarHeight + statusBarHeight
    }
}
