//
//  HMGPenguinInPlatformBridge.swift
//  Runner
//
//  Created by Haroon Amjad on 13/08/2024.
//

import Foundation

var flutterMethodChannelPenguinIn:FlutterMethodChannel? = nil
fileprivate var mainViewController:MainFlutterVC!

class HMGPenguinInPlatformBridge{
    
    private let channelName = "launch_penguin_ui"
    private static var shared_:HMGPenguinInPlatformBridge?
    
    class func initialize(flutterViewController:MainFlutterVC){
        shared_ = HMGPenguinInPlatformBridge()
        mainViewController = flutterViewController
        shared_?.openChannel()
    }
    
    func shared() -> HMGPenguinInPlatformBridge{
        assert((HMGPenguinInPlatformBridge.shared_ != nil), "HMGPenguinInPlatformBridge is not initialized, call initialize(mainViewController:MainFlutterVC) function first.")
        return HMGPenguinInPlatformBridge.shared_!
    }
    
    private func openChannel(){
        flutterMethodChannelPenguinIn = FlutterMethodChannel(name: channelName, binaryMessenger: mainViewController.binaryMessenger)
        
        flutterMethodChannelPenguinIn?.setMethodCallHandler { (methodCall, result) in
            print("Called function \(methodCall.method)")
            
            if let arguments = methodCall.arguments as Any? {
                if methodCall.method == "launchPenguin"{
                    self.launchPenguinView(arguments: arguments, result: result)
                }
            } else {
                result(FlutterError(code: "INVALID_ARGUMENT", message: "Storyboard name is required", details: nil))
            }
        }
    }
    
    private func launchPenguinView(arguments: Any, result: @escaping FlutterResult) {
        let penguinView = PenguinView(
            frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height),
            viewIdentifier: 0,
            arguments: arguments,
            binaryMessenger: mainViewController.binaryMessenger
        )
        
        let penguinUIView = penguinView.view()
        penguinUIView.frame = mainViewController.view.bounds
        penguinUIView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        mainViewController.view.addSubview(penguinUIView)
        
        result(nil) // Call result to indicate the method was successfully handled
    }

}
