import Flutter
import Foundation

@available(iOS 13.0, *)
public class MobileUseStatisticsPlugin: NSObject, FlutterPlugin {
    
    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(
            name: "mobile_use_statistics",
            binaryMessenger: registrar.messenger()
        )
        let instance = MobileUseStatisticsPlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)
    }
    
    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        switch call.method {
        case "getLockScreenStatistics":
            handleGetLockScreenStatistics(call: call, result: result)
            
        case "hasUseStatisticsPermission":
            result(true)
            
        case "requestUseStatisticsPermission":
            result(nil)
            
        case "appLaunchAnActivationPermission":
            BackgroundTaskManager.shared.registerBackgroundTask()
            ScreenLockMonitor.shared.startMonitoringInBackground()
            result(nil)
            
        case "appEntersTheBackenPermission":
            BackgroundTaskManager.shared.scheduleBackgroundTask()
            result(nil)
            
        default:
            result(FlutterMethodNotImplemented)
        }
    }
    
    private func handleGetLockScreenStatistics(call: FlutterMethodCall, result: @escaping FlutterResult) {
        do {
            guard let args = call.arguments as? [String: Any],
                  let startTime = args["startTime"] as? Int,
                  let endTime = args["endTime"] as? Int else {
                throw FlutterError(code: "INVALID_ARGUMENTS",
                                 message: "Required parameters: startTime(Int), endTime(Int)",
                                   details: nil) as! any Error
            }
            
            // 时间戳转换（秒级→Date）
            let startDate = Date(timeIntervalSince1970: TimeInterval(startTime))
            let endDate = Date(timeIntervalSince1970: TimeInterval(endTime))
            
            print("查询时间范围: \(startDate) - \(endDate)")
            
            // 获取事件对
            let eventPairs = EventQueryService.shared.getEventPairsBetween(
                startDate: startDate,
                endDate: endDate
            )
            
            // 转换为Flutter可接收的格式
            let response = eventPairs.map { pair in
                return [
                    "startTime": Int((pair["startTime"]! as AnyObject).timeIntervalSince1970),
                    "endTime": Int((pair["endTime"]! as AnyObject).timeIntervalSince1970)
                ]
            }
            print("responsesfsdfs--A-\(response)")
            result(response)
            
        } catch let error as FlutterError {
            result(error)
        } catch {
            result(FlutterError(code: "UNKNOWN_ERROR",
                              message: error.localizedDescription,
                              details: nil))
        }
    }
}

extension Date {
    /// Flutter时间戳（秒级）
    var flutterTimestamp: Int {
        return Int(timeIntervalSince1970)
    }
    
    /// 从Flutter时间戳初始化
    static func fromFlutterTimestamp(_ timestamp: Int) -> Date {
        return Date(timeIntervalSince1970: TimeInterval(timestamp))
    }
}
