import Flutter
import UIKit

public class SwiftQrScannerPlugin: NSObject, FlutterPlugin {
  var registrar: FlutterPluginRegistrar!

  var viewController: UIViewController!
  var result: FlutterResult?

  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "scanner", binaryMessenger: registrar.messenger())
    let instance = SwiftQrScannerPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
    if let delegate = UIApplication.shared.delegate, let window = delegate.window, let root = window?.rootViewController {
      instance.viewController = root
      instance.registrar = registrar
    }
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
      case "scan":
        self.result = result
        let scannerController = ScannerViewController()
        scannerController.delegate = self
        let navigationController = CSNavigationController(rootViewController: scannerController)
        scannerController.modalPresentationStyle = .fullScreen
        navigationController.modalPresentationStyle = .fullScreen

        if let arguments = call.arguments as? NSDictionary {
           scannerController.arguments = arguments
        }

        if viewController != nil {
          viewController.present(navigationController, animated: true, completion: nil)
        }
      default:
        result(FlutterMethodNotImplemented)
        break
     }
  }
}

extension SwiftQrScannerPlugin: ScannerDelegate {
  func didScanWithResult(code: String) {
    if let channelResult = result {
      channelResult(code as NSString)
    }
  }

  func didFailWithErrorCode(code: String) {
    if let channelResult = result {
      channelResult("")
    }
  }
}

class CSNavigationController: UINavigationController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override var shouldAutorotate: Bool {
        return self.topViewController?.shouldAutorotate ?? false
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
      get {
        return self.topViewController?.supportedInterfaceOrientations ?? UIInterfaceOrientationMask.portrait
      }
    }
}