//
//  ToolboxesApp.swift
//  Toolboxes
//
//  Created by 研发2组 on 2024/9/21.
//

import SwiftUI
import BackgroundTasks

@available(iOS 17.0, *)
@main
struct ToolboxesApp: App {
    @Environment(\.scenePhase) var scenePhase
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    @StateObject private var compassManager = CompassManager()
    init() {
        registerBackgroundTasks()

        
        setupTabBarAppearance()
        
    }
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        } .onChange(of: scenePhase) { newPhase in
            if newPhase == .background {
                Task {
                    // 异步加载数据或执行长时间运行的任务
                    await compassManager.scheduleBackgroundLocationUpdate()
                }
            }
        }
        .environmentObject(compassManager)
    }
    
    // 注册后台任务
    func registerBackgroundTasks() {
        BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.toolboxes.locationUpdate", using: nil) { task in
            // 处理位置更新任务
            
            CompassManager().handleLocationUpdateTask(task: task as! BGAppRefreshTask)
        }
    }
    
    // 设置 TabBar 外观
    func setupTabBarAppearance() {
        let appearance = UITabBarAppearance()
        appearance.stackedLayoutAppearance.normal.iconColor = UIColor(.tab_nor) // 未选中图标颜色
        appearance.stackedLayoutAppearance.normal.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor(.tab_nor)]
        appearance.stackedLayoutAppearance.selected.iconColor = UIColor(.tab_sel)
        appearance.stackedLayoutAppearance.selected.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor(.tab_sel)]
        appearance.shadowColor = .clear
        UITabBar.appearance().standardAppearance = appearance
        UITabBar.appearance().scrollEdgeAppearance = appearance
        UITabBar.appearance().barTintColor = .black
    }
}
