//import Flutter
//import UIKit
//
//@UIApplicationMain
//@objc class AppDelegate: FlutterAppDelegate {
//  override func application(
//    _ application: UIApplication,
//    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
//  ) -> Bool {
//    GeneratedPluginRegistrant.register(with: self)
//      
//    weak var penguin = self.registrar(forPlugin: "penguin")
//    let penguinFactory = PenguinViewFactory(messenger: penguin!.messenger())
//    self.registrar(forPlugin: "PenguinView")!.register(penguinFactory, withId: "penguin_lib")
//    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
//  }
//}



import Flutter
import UIKit

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    var flutterEngine: FlutterEngine?

    
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        flutterEngine = FlutterEngine(name: "my flutter engine")
        guard let flutterEngine = flutterEngine else {
            fatalError("Flutter engine initialization failed")
        }
        flutterEngine.run()
        GeneratedPluginRegistrant.register(with: flutterEngine)
        GeneratedPluginRegistrant.register(with: self)
        let controller: FlutterViewController = window?.rootViewController as! FlutterViewController
        let channel = FlutterMethodChannel(name: "com.aamir/launch_penguin_ui",
                                           binaryMessenger: controller.binaryMessenger)
        
        channel.setMethodCallHandler { [weak self] (call: FlutterMethodCall, result: @escaping FlutterResult) in
            
            if let arguments = call.arguments as? [String: Any],
               let storyboardName = arguments["storyboardName"] as? String {
                if  call.method == "launchPenguin"{
//                    if let penguinModel = PenguinModel(from: arguments) {
//                        self.model = penguinModel
//                        initPenguin(args: penguinModel)
//                    } else {
//                        print("Error: Failed to initialize PenguinModel from arguments")
//                    }
                    self?.launchPenguinView(arguments: arguments, result: result)
                    //let penguinView =
//                    PenguinView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height), viewIdentifier: 0, arguments: arguments, binaryMessenger: controller.binaryMessenger)
                  //  let penguinUIView = penguinView.initPenguin(args: penguinModel)
                 //   penguinUIView.frame = self.view.bounds
                  //  penguinUIView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
                  //  self.view.addSubview(penguinUIView)
                //    self?.launchStoryboard(named: storyboardName, result: result,  arguments: arguments )
                }
                else {
                    result(FlutterMethodNotImplemented)
                }
            } else {
                result(FlutterError(code: "INVALID_ARGUMENT", message: "Storyboard name is required", details: nil))
            }
            
        }
        
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
    
    private func launchStoryboard(named storyboardName: String, result: @escaping FlutterResult, arguments: [String: Any]) {
        let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
        
        guard let flutterEngine = flutterEngine else {
            result(FlutterError(code: "ENGINE_UNAVAILABLE", message: "Flutter engine is not available", details: nil))
            return
        }
        
        guard let viewController = storyboard.instantiateViewController(withIdentifier: "PenguinViewController") as? PenguinViewController else {
            result(FlutterError(code: "INVALID_VIEW_CONTROLLER", message: "Unable to instantiate view controller", details: nil))
            return
        }
        
        // Use the custom initializer
        viewController.setProperties(flutterEngine: flutterEngine, arguments: arguments)
        
        //        let penguinViewController = PenguinViewController(flutterEngine: flutterEngine, arguments: arguments)
        
        if let rootViewController = window?.rootViewController {
            rootViewController.present(viewController, animated: true, completion: nil)
            result("Storyboard \(storyboardName) launched successfully")
        } else {
            result(FlutterError(code: "UNAVAILABLE", message: "Root view controller is not available", details: nil))
        }
    }
    
    
    
    
    private func launchPenguinView(arguments: [String: Any], result: @escaping FlutterResult) {
          guard let controller = window?.rootViewController as? FlutterViewController else {
              result(FlutterError(code: "NO_CONTROLLER", message: "No Flutter view controller found", details: nil))
              return
          }
          
          let penguinView = PenguinView(
              frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height),
              viewIdentifier: 0,
              arguments: arguments,
              binaryMessenger: controller.binaryMessenger
          )
          
        let penguinUIView = penguinView.view()
          penguinUIView.frame = controller.view.bounds
          penguinUIView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
          
          controller.view.addSubview(penguinUIView)
          
          result(nil) // Call result to indicate the method was successfully handled
      }
}
    
//    private func launchStoryboard(named storyboardName: String, result: @escaping FlutterResult, arguments arguments: [String: Any]) {
//        let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
//        guard let viewController = storyboard.instantiateViewController(withIdentifier: "PenguinViewController") as? PenguinViewController else {
//            result(FlutterError(code: "INVALID_VIEW_CONTROLLER", message: "Unable to instantiate view controller", details: nil))
//            return
//        }
//        
//     //   viewController.arguments = arguments
//
//        guard let flutterEngine = flutterEngine else {
//            result(FlutterError(code: "ENGINE_UNAVAILABLE", message: "Flutter engine is not available", details: nil))
//            return
//        }
//
//        viewController.flutterEngine = flutterEngine
//        viewController.arguments = arguments
//
//        if let rootViewController = window?.rootViewController {
//            rootViewController.present(viewController, animated: true, completion: nil)
//            result("Storyboard \(storyboardName) launched successfully")
//        } else {
//            result(FlutterError(code: "UNAVAILABLE", message: "Root view controller is not available", details: nil))
//        }
//    }
//}

