//
//  widget.swift
//  widget
//
//  Created by edy on 2025/4/3.
//

import WidgetKit
import SwiftUI


struct Provider: TimelineProvider {
    
    func placeholder(in context: Context) -> SimpleEntry {
        SimpleEntry(date: Date() , widgets: 0, widgetBattery: 0, widgetStorage: 0, widgetAllSpace: 0 ,widgetUseSpace: 0 ,batteryState: "Off" , isCharging: false)
    }

    func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> Void) {
        let entry = loadSharedData()
        completion(entry)
    }

    func getTimeline(in context: Context, completion: @escaping (Timeline<SimpleEntry>) -> Void) {
        let entry = loadSharedData()
        let timeline = Timeline(entries: [entry], policy: .after(Date().addingTimeInterval(120)))
        completion(timeline)
    }

    private func loadSharedData() -> SimpleEntry {
        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 SimpleEntry(date: Date(), widgets: 0, widgetBattery: 0, widgetStorage: 0 ,widgetAllSpace: 0 ,widgetUseSpace: 0 ,batteryState: "Off" , isCharging: false)
        }
        return SimpleEntry(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 WidgetStyle : Codable {
    var textColor : String
    var lText : String
    var backgound : String
    var LineColor : String
    var icon : String
    var Angle : Double
}

struct SimpleEntry: 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    // 是否在充电
}

func getShowImage(_ entry:SimpleEntry ,_ type:Int) -> String {
    var img = ""
    if type == 0 {
        if (entry.widgets % 10) != 2 {
            img = "img_storage_widgets"
        }else{
            img = "img_storage_widgets_b"
        }
    }else{
        if (entry.widgets % 10) != 2 {
            img = "img_battery_widgets"
        }else{
            img = "img_battery_widgets_b"
        }
    }
    return img
}

func getwidgetStyle(_ entry: SimpleEntry , _ isBattery:Bool = false) -> WidgetStyle {
    var icon = ""
    var lt = "Battery"
    var anag = 0
    if isBattery {
        if (entry.widgets % 10) != 2 {
            icon = "img_battery_widgets"
        }else{
            icon = "img_battery_widgets_b"
        }
        anag = entry.widgetBattery
    }else{
        lt = "Storage"
        if (entry.widgets % 10) != 2 {
            icon = "img_storage_widgets"
        }else{
            icon = "img_storage_widgets_b"
        }
        anag = entry.widgetStorage
    }
    var tcolor = "FFFFFF"
    var bg = "0082FF"
    var line = "FFFFFF"
    if entry.widgets % 10 == 0  {
        
    } else if entry.widgets % 10 == 1 {
        bg = "333333"
        line = "0082FF"
    }else{
        line = "0082FF"
        bg = "FFFFFF"
        tcolor = "0082FF"
    }
    return WidgetStyle(textColor: tcolor, lText: lt, backgound: bg, LineColor: line ,icon:icon ,Angle: Double(anag))
}


func battteryColor(entry:SimpleEntry) -> Color {
    if entry.widgets % 10 == 0 {
        return .white
    }else if entry.widgets % 10 == 1 {
        return .white
    }else{
        return .black
    }
}

fileprivate func useSpaceColor(entry:SimpleEntry) -> Color {
    if entry.widgets % 10 == 0 {
        return .white
    }else if entry.widgets % 10 == 1 {
        return Color("4AE2FF")
    }else{
        return Color("0082FF")
    }
}

func ActionColor(entry:SimpleEntry) -> Color {
    if entry.isCharging {
        if entry.widgets % 10 == 0 {
            return .white
        }else if entry.widgets % 10 == 1 {
            return Color("4AE2FF")
        }else{
            return Color("0082FF")
        }
    }else{
        return Color("cccccc")
    }
}

fileprivate func PowerColor(entry:SimpleEntry) -> Color {
    if entry.batteryState == "On" {
        if entry.widgets % 10 == 0 {
            return .white
        }else if entry.widgets % 10 == 1 {
            return Color("4AE2FF")
        }else{
            return Color("666666")
        }
    }else{
        return Color("cccccc")
    }
}

fileprivate func contentStack(_ entry:SimpleEntry) -> some View {
    return ZStack {
        Color(getwidgetStyle(entry).backgound).ignoresSafeArea()
        VStack(spacing: 50 ,  content: {
            HStack(alignment: .center, content: {
                VStack(spacing: 5, content: {
                    Text("Storage").frame(maxWidth: .infinity ,alignment: .topLeading).font(.system(size: 18,weight: .medium)).foregroundColor(battteryColor(entry: entry))
                    Text(String(entry.widgetStorage) + "%").frame(maxWidth: .infinity ,alignment: .topLeading).foregroundColor(battteryColor(entry: entry)).font(.system(size: 24,weight: .bold))
                    Text("Used").frame(maxWidth: .infinity ,alignment: .topLeading).foregroundColor(Color("CCCCCC")).font(.system(size: 20,weight: .bold))
                    Text(String(entry.widgetUseSpace) + " of " +  String(entry.widgetAllSpace) + "GB").frame(maxWidth: .infinity ,alignment: .topLeading).foregroundColor(useSpaceColor(entry: entry)).font(.system(size: 18, weight: .bold))
                })
                ZStack {
                    Image(getShowImage(entry, 0))
                    ArcShape(startAngle: .degrees(-90), endAngle: .degrees( Double(entry.widgetStorage)/100.0 * 360.0 - 90.0), clockwise: false).stroke(Color(getwidgetStyle(entry).LineColor), style: StrokeStyle(lineWidth: 5, lineCap: .round) )
                }.frame(width: 68, height: 68, alignment: .center)
            })
            HStack(alignment: .center, content: {
                VStack(spacing: 15, content: {
                    VStack(spacing: 1) {
                        Text("Battery").frame(maxWidth: .infinity ,alignment: .topLeading).font(.system(size: 18,weight: .medium)).foregroundColor(battteryColor(entry: entry))
                        Text(String(entry.widgetBattery) + "%").frame(maxWidth: .infinity ,alignment: .topLeading).foregroundColor(battteryColor(entry: entry)).font(.system(size: 24,weight: .bold))
                    }
                    VStack(spacing: 1) {
                        Text(entry.isCharging ? "Charging now" : "No action").frame(maxWidth: .infinity ,alignment: .topLeading).foregroundColor(ActionColor(entry: entry)).font(.system(size: 20,weight: .medium))
                        Text("Low Power Mode \(entry.batteryState)").frame(maxWidth: .infinity ,alignment: .topLeading).foregroundColor(PowerColor(entry: entry)).font(.system(size: 16, weight: .medium))
                    }
                })
                ZStack {
                    Image(getShowImage(entry, 1))
                    ArcShape(startAngle: .degrees(-90), endAngle: .degrees(Double(entry.widgetBattery)/100.0 * 360.0 - 90.0), clockwise: false).stroke(Color(getwidgetStyle(entry).LineColor), style: StrokeStyle(lineWidth: 5, lineCap: .round))
                }.frame(width: 68, height: 68, alignment: .center)
            })
        }).padding(EdgeInsets(top: 10, leading: 20, bottom: 10, trailing: 30))
    }
}

struct BatteryWidgetBothView : View {
    var entry: Provider.Entry
    var body: some View {
        if #available(iOSApplicationExtension 17.0, *) {
            contentStack(entry).containerBackground(for: .widget) {
                Color(getwidgetStyle(entry).backgound)
            }
        } else {
            contentStack(entry)
        }
    }
}

struct BatteryWidgetView : View {
    var entry: Provider.Entry
    var body: some View {
        if #available(iOSApplicationExtension 17.0, *) {
            ZStack {
                Color(getwidgetStyle(entry).backgound).ignoresSafeArea()
                VStack {
                    HStack(alignment: .center) {
                        Text(getwidgetStyle(entry).lText).frame(maxWidth: .infinity,maxHeight: .infinity,alignment: .topLeading).font(.system(size: 14)).foregroundColor(Color(getwidgetStyle(entry).textColor))
                        VStack(alignment: .center, spacing: 2) {
                            Text(String(getwidgetStyle(entry).Angle) + "%" ).frame(maxWidth: .infinity,maxHeight: .infinity,alignment: .topTrailing).font(.system(size: 14)).foregroundColor(Color(getwidgetStyle(entry).textColor))
                            if entry.widgets / 10 == 1 {
                                Text("Used").frame(maxWidth: .infinity,alignment: .topTrailing).font(.system(size: 10)).foregroundColor(Color(getwidgetStyle(entry).textColor)).padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 5))
                            }
                        }
                    }
                    ZStack {
                        Image(getwidgetStyle(entry).icon)
                        ArcShape(startAngle: .degrees(-90), endAngle: .degrees(getwidgetStyle(entry).Angle/100.0 * 360.0 - 90.0), clockwise: false)
                            .stroke(Color(getwidgetStyle(entry).LineColor), style: StrokeStyle(lineWidth: 5, lineCap: .round) )
                    }
                }.padding(EdgeInsets(top: 16, leading: 0, bottom: 30, trailing: 0))
            }
            .containerBackground(for: .widget) {
                Color(getwidgetStyle(entry).backgound)
            }
        } else {
            ZStack {
                Color(getwidgetStyle(entry).backgound).ignoresSafeArea()
                VStack {
                    HStack(alignment: .center) {
                        Text(getwidgetStyle(entry).lText).frame(maxWidth: .infinity,maxHeight: .infinity,alignment: .topLeading).font(.system(size: 14)).foregroundColor(Color(getwidgetStyle(entry).textColor))
                        VStack(alignment: .center, spacing: 2) {
                            Text(String(getwidgetStyle(entry).Angle) + "%" ).frame(maxWidth: .infinity,maxHeight: .infinity,alignment: .topTrailing).font(.system(size: 14)).foregroundColor(Color(getwidgetStyle(entry).textColor))
                            if entry.widgets / 10 == 1 {
                                Text("Used").frame(maxWidth: .infinity,alignment: .topTrailing).font(.system(size: 10)).foregroundColor(Color(getwidgetStyle(entry).textColor)).padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 5))
                            }
                        }
                    }
                    ZStack {
                        Image(getwidgetStyle(entry).icon)
                        ArcShape(startAngle: .degrees(-90), endAngle: .degrees(getwidgetStyle(entry).Angle/100.0 * 360.0 - 90.0), clockwise: false)
                            .stroke(Color(getwidgetStyle(entry).LineColor), style: StrokeStyle(lineWidth: 5, lineCap: .round) )
                    }
                }.padding(EdgeInsets(top: 16, leading: 10, bottom: 30, trailing: 10))
            }
        }
    }
}

struct BatteryWidgetStorageView : View {
    var entry: Provider.Entry
    var body: some View {
        if #available(iOSApplicationExtension 17.0, *) {
            ZStack {
                Color(getwidgetStyle(entry,true).backgound).ignoresSafeArea()
                VStack {
                    HStack(alignment: .center) {
                        Text(getwidgetStyle(entry,true).lText).frame(maxWidth: .infinity,maxHeight: .infinity,alignment: .topLeading).font(.system(size: 14)).foregroundColor(Color(getwidgetStyle(entry,true).textColor))
                        VStack(alignment: .center, spacing: 2) {
                            Text(String(getwidgetStyle(entry,true).Angle) + "%" ).frame(maxWidth: .infinity,maxHeight: .infinity,alignment: .topTrailing).font(.system(size: 14)).foregroundColor(Color(getwidgetStyle(entry,true).textColor))
                            if entry.widgets / 10 == 1 {
                                Text("Used").frame(maxWidth: .infinity,alignment: .topTrailing).font(.system(size: 10)).foregroundColor(Color(getwidgetStyle(entry,true).textColor)).padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 5))
                            }
                        }
                    }
                    ZStack {
                        Image(getwidgetStyle(entry,true).icon)
                        ArcShape(startAngle: .degrees(-90), endAngle: .degrees(getwidgetStyle(entry,true).Angle/100.0 * 360.0 - 90.0), clockwise: false)
                            .stroke(Color(getwidgetStyle(entry,true).LineColor), style: StrokeStyle(lineWidth: 5, lineCap: .round) )
                    }
                }.padding(EdgeInsets(top: 16, leading: 0, bottom: 30, trailing: 0))
            }
            .containerBackground(for: .widget) {
                Color(getwidgetStyle(entry,true).backgound)
            }
        } else {
            ZStack {
                Color(getwidgetStyle(entry,true).backgound).ignoresSafeArea()
                VStack {
                    HStack(alignment: .center) {
                        Text(getwidgetStyle(entry,true).lText).frame(maxWidth: .infinity,maxHeight: .infinity,alignment: .topLeading).font(.system(size: 14)).foregroundColor(Color(getwidgetStyle(entry,true).textColor))
                        VStack(alignment: .center, spacing: 2) {
                            Text(String(getwidgetStyle(entry,true).Angle) + "%" ).frame(maxWidth: .infinity,maxHeight: .infinity,alignment: .topTrailing).font(.system(size: 14)).foregroundColor(Color(getwidgetStyle(entry,true).textColor))
                            if entry.widgets / 10 == 1 {
                                Text("Used").frame(maxWidth: .infinity,alignment: .topTrailing).font(.system(size: 10)).foregroundColor(Color(getwidgetStyle(entry,true).textColor)).padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 5))
                            }
                        }
                    }
                    ZStack {
                        Image(getwidgetStyle(entry,true).icon)
                        ArcShape(startAngle: .degrees(-90), endAngle: .degrees(getwidgetStyle(entry,true).Angle/100.0 * 360.0 - 90.0), clockwise: false)
                            .stroke(Color(getwidgetStyle(entry,true).LineColor), style: StrokeStyle(lineWidth: 5, lineCap: .round) )
                    }
                }.padding(EdgeInsets(top: 16, leading: 10, bottom: 30, trailing: 10))
            }
        }
    }
}


struct EmptyView : View {
    var body: some View {
        ZStack {
            Color.clear.ignoresSafeArea()
            Text("").foregroundColor(.clear)
        }
    }
}

struct BatteryWidgetEntryView : View {
    var entry: Provider.Entry
    @Environment(\.widgetFamily) var family
    var body: some View {
        switch family {
        case .systemSmall:
            BatteryWidgetView(entry: entry)
        case .systemMedium:
            BatteryWidgetView(entry: entry)
        case .systemLarge:
            BatteryWidgetBothView(entry: entry)
        default:
            EmptyView()
        }
    }
}

struct BatteryStorageEntryView : View {
    var entry: Provider.Entry
    @Environment(\.widgetFamily) var family
    var body: some View {
        switch family {
        case .systemSmall:
            BatteryWidgetStorageView(entry: entry)
        case .systemMedium:
            BatteryWidgetStorageView(entry: entry)
        case .systemLarge:
            BatteryWidgetBothView(entry: entry)
        default:
            EmptyView()
        }
    }
}

struct ArcShape: Shape {
    var startAngle: Angle
    var endAngle: Angle
    var clockwise: Bool
    func path(in rect: CGRect) -> Path {
        var path = Path()
        let center = CGPoint(x: rect.midX, y: rect.midY)
        let radius = min(rect.width, rect.height) / 2.0 - 3.0
        path.addArc(
            center: center,
            radius: radius,
            startAngle: startAngle,
            endAngle: endAngle,
            clockwise: clockwise
        )
        return path
    }
}

struct BatteryWidget: Widget {
    let kind: String = "BatteryWidget"
    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind, provider: Provider()) { entry in
            BatteryWidgetEntryView(entry: entry)
        }.configurationDisplayName("Storage").description("Monitor your storage space")
            .supportedFamilies([.systemSmall ,.systemMedium])
    }
}

struct BatteryWidget1: Widget {
    let kind: String = "BatteryWidget1"
    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind, provider: Provider()) { entry in
            BatteryStorageEntryView(entry: entry)
        }.configurationDisplayName("Battery").description("Monitor your battery")
            .supportedFamilies([.systemSmall ,.systemMedium])
    }
}

struct BatteryWidget2: Widget {
    let kind: String = "BatteryWidget2"
    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind, provider: Provider()) { entry in
            BatteryStorageEntryView(entry: entry)
        }.configurationDisplayName("Both").description("Monitor your battery and storage space")
            .supportedFamilies([.systemLarge])
    }
}






//struct AWidgetStorageView : View {
//    var entry: Provider.Entry
//    var body: some View {
//        if #available(iOSApplicationExtension 17.0, *) {
//            ZStack {
//                Text("\(entry.widgetBattery)")
//            }.foregroundColor(Color("333333"))
//            .containerBackground(for: .widget) {
//                AccessoryWidgetBackground()
//            }
//        } else {
//            ZStack {
//                Text("Hello")
//            }
//        }
//    }
//}


//struct LockScreenWidgetView :View {
//    var entry: Provider.Entry
//    @Environment(\.widgetFamily) var family
//    var body: some View {
//        switch family {
//        case .accessoryCircular:
//            AWidgetStorageView(entry: entry)
//        default:
//            EmptyView()
//        }
//    }
//}


//struct widgetLockSreenView: Widget {
//    let kind = "com.app.lockscreen.widget"
//    var body: some WidgetConfiguration {
//        if #available(iOSApplicationExtension 16.0, *) {
//            StaticConfiguration(kind: kind, provider: Provider()) { entry in
//                LockScreenWidgetView(entry: entry)
//            }
//            .configurationDisplayName("Storage")
//            .description("Monitor your storage space")
//            .supportedFamilies([
//                .accessoryCircular,
//            ])
//        } else {
//            StaticConfiguration(kind: kind, provider: Provider()) { entry in
//                LockScreenWidgetView(entry: entry)
//            }
//            .configurationDisplayName("")
//            .description("")
//            .supportedFamilies([])
//        }
//    }
//}
