//
//  BatteryMonitorManager.swift
//  PhoneManager
//
//  Created by edy on 2025/3/27.
//

import UIKit

protocol BatteryStatusDelegate: AnyObject {
    func batteryStatusDidUpdate(level: Float, state: UIDevice.BatteryState)
}

class BatteryMonitorManager {
    
    // Singleton instance
    static let shared = BatteryMonitorManager()
    
    // Delegate for status updates
    weak var delegate: BatteryStatusDelegate?
    
    // Current battery level (0.0 to 1.0)
    private(set) var batteryLevel: Float = 0.0
    
    // Current battery state
    private(set) var batteryState: UIDevice.BatteryState = .unknown
    
    // Flag to track if monitoring is active
    private var isMonitoring = false
    
    private init() {
        // Private initializer for singleton
    }
    
    // MARK: - Public Methods
    
    /// Start monitoring battery status
    func startMonitoring() {
        guard !isMonitoring else { return }
        
        UIDevice.current.isBatteryMonitoringEnabled = true
        
        // Get initial values
        updateBatteryStatus()
        
        // Register for notifications
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(batteryLevelDidChange),
            name: UIDevice.batteryLevelDidChangeNotification,
            object: nil
        )
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(batteryStateDidChange),
            name: UIDevice.batteryStateDidChangeNotification,
            object: nil
        )
        
        isMonitoring = true
    }
    
    /// Stop monitoring battery status
    func stopMonitoring() {
        guard isMonitoring else { return }
        
        NotificationCenter.default.removeObserver(self)
        UIDevice.current.isBatteryMonitoringEnabled = false
        
        isMonitoring = false
        print("Battery monitoring stopped")
    }
    
    /// Get current battery status as a formatted string
//    func currentBatteryStatus() -> String {
//        let levelPercent = Int(batteryLevel * 100)
//        let stateString = batteryStateDescription()
//        
//        return "Battery: \(levelPercent)% (\(stateString))"
//    }
    
    func getBatteryIsCharging() -> Bool {
        
        UIDevice.current.isBatteryMonitoringEnabled = true
        switch UIDevice.current.batteryState {
        case.unknown:
            print("电池状态未知")
        case.unplugged:
            print("电池未充电")
        case.charging:
            print("电池正在充电")
        case.full:
            print("电池已充满")
        @unknown default:
            break
        }
        return UIDevice.current.batteryState == .charging || UIDevice.current.batteryState == .full
    }
    
    // MARK: - Private Methods
    
    @objc private func batteryLevelDidChange() {
        updateBatteryStatus()
    }
    
    @objc private func batteryStateDidChange() {
        updateBatteryStatus()
    }
    
    private func updateBatteryStatus() {
        batteryLevel = UIDevice.current.batteryLevel
        batteryState = UIDevice.current.batteryState
        
        // Notify delegate
        delegate?.batteryStatusDidUpdate(level: batteryLevel, state: batteryState)
        
        // Print to console (for debugging)
    }
    
    private func batteryStateDescription() -> String {
        switch batteryState {
        case .unknown:
            return "Unknown"
        case .unplugged:
            return "Unplugged"
        case .charging:
            return "Charging"
        case .full:
            return "Full"
        @unknown default:
            return "Unknown state"
        }
    }
    
    deinit {
        stopMonitoring()
    }
}
