//
//  LockSreenModel.swift
//  widget
//
//  Created by Flower on 2025/5/10.
//

import WidgetKit
import SwiftUI

struct LockSreenProvider: TimelineProvider {
    func placeholder(in context: Context) -> LockSreenEntry {
        return LockSreenEntry(date: .now, widgets: 0, widgetBattery: 1, widgetStorage: 1, widgetAllSpace: 1, widgetUseSpace: 1, batteryState: "Off", isCharging: false)
    }

    func getSnapshot(in context: Context, completion: @escaping (LockSreenEntry) -> ()) {
        let entry = LockSreenEntry(date: .now, widgets: 1, widgetBattery: 1, widgetStorage: 1, widgetAllSpace: 1, widgetUseSpace: 1, batteryState: "Off", isCharging: false)
        completion(entry)
    }

    func getTimeline(in context: Context, completion: @escaping (Timeline<LockSreenEntry>) -> ()) {
        let entry = loadSharedData()
        let timeline = Timeline(entries: [entry], policy: .after(Date().addingTimeInterval(100)))
        completion(timeline)
    }
    
    private func loadSharedData() -> LockSreenEntry {
        guard let sharedDefaults = UserDefaults(suiteName: "group.com.app.phonemanager"),
              let data:Data = sharedDefaults.object(forKey: "widgetSharedData") as? Data,
              let decodedData = try? JSONDecoder().decode(WidgetData.self, from: data)
        else {
            return LockSreenEntry(date: Date(), widgets: 0, widgetBattery: 0, widgetStorage: 0 ,widgetAllSpace: 1 ,widgetUseSpace: 0 ,batteryState: "Off" , isCharging: false)
        }
        return LockSreenEntry(date: Date(), widgets: decodedData.widget, widgetBattery: decodedData.battery, widgetStorage: decodedData.widgetStorage,widgetAllSpace: decodedData.AllSpace,widgetUseSpace: decodedData.UseSpace ,batteryState: decodedData.batteryState ,isCharging: decodedData.isCharging)
    }
    
}


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
}

struct LockSreenEntry: TimelineEntry {
    let date: Date
    var widgets:Int
    let widgetBattery:Int
    let widgetStorage:Int
    let widgetAllSpace:Int
    let widgetUseSpace:Int
    let batteryState: String  // 是否低电量模式
    let isCharging: Bool    // 是否在充电
}

// 单一
struct lockSreenType {
    var type:Int = 0               // 正方形 长方形
    var isStorage:Bool = false     // 是否是存储
    
    var kind:String = ""
    var displayName:String = ""
    var description:String = ""
}
