//
//  WidgetPublicModel.swift
//  PhoneManager
//
//  Created by edy on 2025/4/2.
//

import UIKit
import Foundation
import Darwin
import WidgetKit


class WidgetPublicModel: NSObject {
    
    public class func battery() -> Float {
        let device = UIDevice.current
        device.isBatteryMonitoringEnabled = true
        let batt = device.batteryLevel * 100;
        return batt
    }
    
    public class func BatteryState() -> Bool {
        let device = UIDevice.current
        device.isBatteryMonitoringEnabled = true
        switch device.batteryState {
        case .charging:
            return true
        default:
            return false
        }
    }
    
    
    
    /// 已使用
    /// - Returns: 已使用空间
    public class func UseDiskSpace() -> CGFloat {
        let disk = getDiskSpace()
        let use = disk.0 - disk.1
        let useP:CGFloat = CGFloat(use) / CGFloat(disk.0)
        return useP
    }
    
    
    /// 获取总共和可用空间
    /// - Returns: 总共和可用空间
    public class func getDiskSpace() -> (Int64,Int64) {
        let total = TotalDiskSize()
        let available = AvailableDiskSize()
        return (total,available)
    }
     
    // 硬盘总大小
    class func TotalDiskSize() -> Int64 {
        var fs = blankof(type: statfs.self)
        if statfs("/var",&fs) >= 0 {
            return Int64(UInt64(fs.f_bsize) * fs.f_blocks)
        }
        return -1
    }
    // 硬盘剩余大小
    class func AvailableDiskSize() -> Int64 {
        do {
            let fileURL = URL(fileURLWithPath: NSHomeDirectory())
            let values = try fileURL.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])
            if let availableSpace = values.volumeAvailableCapacityForImportantUsage {
                return Int64(availableSpace)
            }
        } catch {
            print("获取磁盘空间信息时出错: \(error)")
            return -1
        }
        return -1
    }
    
    class private func blankof<T>(type:T.Type) -> T {
        let ptr = UnsafeMutablePointer<T>.allocate(capacity: MemoryLayout<T>.size)
        let val = ptr.pointee
        return val
    }
    
    class func isLowPowerModeEnabled() -> Bool {
        return ProcessInfo.processInfo.isLowPowerModeEnabled
    }
    
}

class widgetAppgourp: NSObject {

    static let share = widgetAppgourp()
    
    func PushWidgetData(_ widget:Int = 0 , battery:Int , storage:Int ) -> Void {
        
        let disk = WidgetPublicModel.getDiskSpace()
        let allInt = Int(CGFloat(disk.0)/(1000.0 * 1000.0 * 1000.0))
        let useInt = Int(CGFloat(disk.0 - disk.1)/(1000.0 * 1000.0 * 1000.0))
        let state = (WidgetPublicModel.isLowPowerModeEnabled() ? "On" : "Off")
        let data = WidgetData(userId: "", widget: widget, battery: battery, widgetStorage: storage,AllSpace: allInt , UseSpace: useInt ,batteryState:state ,isCharging: WidgetPublicModel.BatteryState())
            if let sharedDefaults = UserDefaults(suiteName: "group.com.app.phonemanager") {
            let encodedData = try? JSONEncoder().encode(data)
                sharedDefaults.set(encodedData, forKey: "widgetSharedData")
        }
        WidgetCenter.shared.reloadAllTimelines()
    }
    
}


struct WidgetData: Codable {
    var userId: String
    var widget: Int
    var battery: Int
    var widgetStorage :Int
    var AllSpace: Int
    var UseSpace: Int
    let batteryState: String
    let isCharging: Bool
}
