import Flutter
import UIKit
import GoogleMaps

@main
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    if let apiKey = getDartDefine(key: "GOOGLE_MAPS_API_KEY") {
      GMSServices.provideAPIKey(apiKey)
    }
    
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

  private func getDartDefine(key: String) -> String? {
    guard let dartDefines = Bundle.main.infoDictionary?["DART_DEFINES"] as? String else {
      return nil
    }
    
    let defines = dartDefines.components(separatedBy: ",")
    for define in defines {
      guard let decodedData = Data(base64Encoded: define),
            let decodedString = String(data: decodedData, encoding: .utf8) else {
        continue
      }
      
      let components = decodedString.components(separatedBy: "=")
      if components.count == 2 && components[0] == key {
        return components[1]
      }
    }
    return nil
  }
}
