//
//  TSFlashlightController.swift
//  Girly
//
//  Created by 100Years on 2025/1/9.
//

import AVFoundation

class TSFlashlightController {
    private var isFlashing = false
    private var timer: DispatchSourceTimer?
    
    /// 开始闪烁闪光灯
    /// - Parameters:
    ///   - frequency: 闪烁频率（每秒闪烁次数，默认为 2 次）
    func startFlashing(frequency: Double = 2.0) {
        guard let device = AVCaptureDevice.default(for: .video), device.hasTorch else {
            print("设备不支持闪光灯")
            return
        }
        
        stopFlashing() // 确保之前的定时器已清除
        
        isFlashing = true
        let interval = 1.0 / frequency
        
        // 创建 GCD 定时器
        timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
        timer?.schedule(deadline: .now(), repeating: interval)
        timer?.setEventHandler { [weak self] in
            guard let self = self else { return }
            self.toggleTorch()
        }
        timer?.resume()
    }
    
    /// 停止闪烁闪光灯
    func stopFlashing() {
        isFlashing = false
        timer?.cancel()
        timer = nil
        setTorch(on: false)
    }
    
    /// 设置闪光灯状态
    /// - Parameter on: 是否打开闪光灯
    private func setTorch(on: Bool) {
        guard let device = AVCaptureDevice.default(for: .video), device.hasTorch else { return }
        do {
            try device.lockForConfiguration()
            device.torchMode = on ? .on : .off
            device.unlockForConfiguration()
        } catch {
            print("无法配置闪光灯: \(error.localizedDescription)")
        }
    }
    
    /// 切换闪光灯状态
    private func toggleTorch() {
        guard let device = AVCaptureDevice.default(for: .video), device.hasTorch else { return }
        do {
            try device.lockForConfiguration()
            device.torchMode = (device.torchMode == .on) ? .off : .on
            device.unlockForConfiguration()
        } catch {
            print("无法切换闪光灯: \(error.localizedDescription)")
        }
    }
}
