//
//  TSFlashlightTool.swift
//  Girly
//
//  Created by 100Years on 2025/1/10.
//

import AVFoundation

class TSFlashlightTool {
    
    /// 开启手电筒
    /// - Parameter brightness: 手电筒亮度（0.01 最暗，1.0 最亮）
    func turnOn(brightness: Float = 1.0) {
        guard let device = AVCaptureDevice.default(for: .video), device.hasTorch else {
            print("设备不支持手电筒")
            return
        }
        
        do {
            try device.lockForConfiguration()
            let validBrightness = clamp(brightness, min: 0.01, max: 1.0) // 调整最小值为 0.01
            try device.setTorchModeOn(level: validBrightness)
            device.unlockForConfiguration()
        } catch {
            print("无法开启手电筒: \(error.localizedDescription)")
        }
    }
    
    /// 关闭手电筒
    func turnOff() {
        guard let device = AVCaptureDevice.default(for: .video), device.hasTorch else {
            print("设备不支持手电筒")
            return
        }
        
        do {
            try device.lockForConfiguration()
            device.torchMode = .off
            device.unlockForConfiguration()
        } catch {
            print("无法关闭手电筒: \(error.localizedDescription)")
        }
    }
    
    /// 调整手电筒亮度
    /// - Parameter brightness: 手电筒亮度（0.01 最暗，1.0 最亮）
    func adjustBrightness(brightness: Float) {
        guard let device = AVCaptureDevice.default(for: .video), device.hasTorch else {
            print("设备不支持手电筒")
            return
        }
        
        do {
            try device.lockForConfiguration()
            if device.torchMode == .on {
                let validBrightness = clamp(brightness, min: 0.01, max: 1.0) // 调整最小值为 0.01
                try device.setTorchModeOn(level: validBrightness)
            } else {
                print("手电筒未开启，无法调整亮度")
            }
            device.unlockForConfiguration()
        } catch {
            print("无法调整手电筒亮度: \(error.localizedDescription)")
        }
    }
    
    /// 约束值范围
    /// - Parameters:
    ///   - value: 原始值
    ///   - min: 最小值
    ///   - max: 最大值
    /// - Returns: 约束后的值
    private func clamp(_ value: Float, min: Float, max: Float) -> Float {
        return Swift.max(min, Swift.min(max, value))
    }
}
