import UIKit
import Flutter
import flutter_local_notifications
import AdSupport
import AppTrackingTransparency
import home_widget

@main
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {

  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
      let result = super.application(application, didFinishLaunchingWithOptions: launchOptions)
      applySavedThemeMode()
      return result
  }

  // Forces the window's interface style to match the user's saved theme
  // preference (read from `shared_preferences`) so the native splash overlay
  // follows the in-app choice instead of only the OS brightness.
  private func applySavedThemeMode() {
      let saved = UserDefaults.standard.string(forKey: "flutter.themeMode")
      let style: UIUserInterfaceStyle
      switch saved {
      case "dark": style = .dark
      case "light": style = .light
      default: style = .unspecified
      }
      window?.overrideUserInterfaceStyle = style
  }

  func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
      GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)

      let advertisingChannel = FlutterMethodChannel(
          name: "kasy_kit/advertising_id",
          binaryMessenger: engineBridge.applicationRegistrar.messenger()
      )
      
      advertisingChannel.setMethodCallHandler({
        (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
        if call.method == "getAdvertisingId" {
          if #available(iOS 14.5, *) {
            let status = ATTrackingManager.trackingAuthorizationStatus
            if status == .authorized {
              let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
              if ASIdentifierManager.shared().isAdvertisingTrackingEnabled {
                result(idfa)
              } else {
                result("")
              }
            } else {
              result("")
            }
          } else {
            if ASIdentifierManager.shared().isAdvertisingTrackingEnabled {
              let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
              result(idfa)
            } else {
              result("")
            }
          }
        } else {
          result(FlutterMethodNotImplemented)
        }
      })
      
      FlutterLocalNotificationsPlugin.setPluginRegistrantCallback { (registry) in
          GeneratedPluginRegistrant.register(with: registry)
      }
      
      // for interactive widgets
      // if #available(iOS 17, *) {
      //   HomeWidgetBackgroundWorker.setPluginRegistrantCallback { registry in
      //     GeneratedPluginRegistrant.register(with: registry)
      //   }
      // }
      
      if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
      }
      
      // if #available(iOS 17.0, *) {
      //   HomeWidgetPlugin.setConfigurationLookup(to: [
      //     "ConfigurableWidget": ConfigurationAppIntent.self
      //   ])
      // }
  }
}
