// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Autogenerated from Pigeon (v22.6.4), do not edit directly.
// See also: https://pub.dev/packages/pigeon

import Foundation

#if os(iOS)
  import Flutter
#elseif os(macOS)
  import FlutterMacOS
#else
  #error("Unsupported platform.")
#endif

/// Error class for passing custom error details to Dart side.
final class PigeonError: Error {
  let code: String
  let message: String?
  let details: Any?

  init(code: String, message: String?, details: Any?) {
    self.code = code
    self.message = message
    self.details = details
  }

  var localizedDescription: String {
    return
      "PigeonError(code: \(code), message: \(message ?? "<nil>"), details: \(details ?? "<nil>")"
  }
}

private func wrapResult(_ result: Any?) -> [Any?] {
  return [result]
}

private func wrapError(_ error: Any) -> [Any?] {
  if let pigeonError = error as? PigeonError {
    return [
      pigeonError.code,
      pigeonError.message,
      pigeonError.details,
    ]
  }
  if let flutterError = error as? FlutterError {
    return [
      flutterError.code,
      flutterError.message,
      flutterError.details,
    ]
  }
  return [
    "\(error)",
    "\(type(of: error))",
    "Stacktrace: \(Thread.callStackSymbols)",
  ]
}

private func isNullish(_ value: Any?) -> Bool {
  return value is NSNull || value == nil
}

private func nilOrValue<T>(_ value: Any?) -> T? {
  if value is NSNull { return nil }
  return value as! T?
}

/// Possible outcomes of launching a URL.
enum LaunchResult: Int {
  /// The URL was successfully launched (or could be, for `canLaunchUrl`).
  case success = 0
  /// There was no handler available for the URL.
  case failure = 1
  /// The URL could not be launched because it is invalid.
  case invalidUrl = 2
}

/// Possible outcomes of handling a URL within the application.
enum InAppLoadResult: Int {
  /// The URL was successfully loaded.
  case success = 0
  /// The URL did not load successfully.
  case failedToLoad = 1
  /// The URL could not be launched because it is invalid.
  case invalidUrl = 2
  /// The controller was closed before loading.
  case dismissed = 3
}

private class messagesPigeonCodecReader: FlutterStandardReader {
  override func readValue(ofType type: UInt8) -> Any? {
    switch type {
    case 129:
      let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?)
      if let enumResultAsInt = enumResultAsInt {
        return LaunchResult(rawValue: enumResultAsInt)
      }
      return nil
    case 130:
      let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?)
      if let enumResultAsInt = enumResultAsInt {
        return InAppLoadResult(rawValue: enumResultAsInt)
      }
      return nil
    default:
      return super.readValue(ofType: type)
    }
  }
}

private class messagesPigeonCodecWriter: FlutterStandardWriter {
  override func writeValue(_ value: Any) {
    if let value = value as? LaunchResult {
      super.writeByte(129)
      super.writeValue(value.rawValue)
    } else if let value = value as? InAppLoadResult {
      super.writeByte(130)
      super.writeValue(value.rawValue)
    } else {
      super.writeValue(value)
    }
  }
}

private class messagesPigeonCodecReaderWriter: FlutterStandardReaderWriter {
  override func reader(with data: Data) -> FlutterStandardReader {
    return messagesPigeonCodecReader(data: data)
  }

  override func writer(with data: NSMutableData) -> FlutterStandardWriter {
    return messagesPigeonCodecWriter(data: data)
  }
}

class messagesPigeonCodec: FlutterStandardMessageCodec, @unchecked Sendable {
  static let shared = messagesPigeonCodec(readerWriter: messagesPigeonCodecReaderWriter())
}

/// Generated protocol from Pigeon that represents a handler of messages from Flutter.
protocol UrlLauncherApi {
  /// Checks whether a URL can be loaded.
  func canLaunchUrl(url: String) throws -> LaunchResult
  /// Opens the URL externally, returning the status of launching it.
  func launchUrl(
    url: String, universalLinksOnly: Bool,
    completion: @escaping (Result<LaunchResult, Error>) -> Void)
  /// Opens the URL in an in-app SFSafariViewController, returning the results
  /// of loading it.
  func openUrlInSafariViewController(
    url: String, completion: @escaping (Result<InAppLoadResult, Error>) -> Void)
  /// Closes the view controller opened by [openUrlInSafariViewController].
  func closeSafariViewController() throws
}

/// Generated setup class from Pigeon to handle messages through the `binaryMessenger`.
class UrlLauncherApiSetup {
  static var codec: FlutterStandardMessageCodec { messagesPigeonCodec.shared }
  /// Sets up an instance of `UrlLauncherApi` to handle messages through the `binaryMessenger`.
  static func setUp(
    binaryMessenger: FlutterBinaryMessenger, api: UrlLauncherApi?, messageChannelSuffix: String = ""
  ) {
    let channelSuffix = messageChannelSuffix.count > 0 ? ".\(messageChannelSuffix)" : ""
    /// Checks whether a URL can be loaded.
    let canLaunchUrlChannel = FlutterBasicMessageChannel(
      name: "dev.flutter.pigeon.url_launcher_ios.UrlLauncherApi.canLaunchUrl\(channelSuffix)",
      binaryMessenger: binaryMessenger, codec: codec)
    if let api = api {
      canLaunchUrlChannel.setMessageHandler { message, reply in
        let args = message as! [Any?]
        let urlArg = args[0] as! String
        do {
          let result = try api.canLaunchUrl(url: urlArg)
          reply(wrapResult(result))
        } catch {
          reply(wrapError(error))
        }
      }
    } else {
      canLaunchUrlChannel.setMessageHandler(nil)
    }
    /// Opens the URL externally, returning the status of launching it.
    let launchUrlChannel = FlutterBasicMessageChannel(
      name: "dev.flutter.pigeon.url_launcher_ios.UrlLauncherApi.launchUrl\(channelSuffix)",
      binaryMessenger: binaryMessenger, codec: codec)
    if let api = api {
      launchUrlChannel.setMessageHandler { message, reply in
        let args = message as! [Any?]
        let urlArg = args[0] as! String
        let universalLinksOnlyArg = args[1] as! Bool
        api.launchUrl(url: urlArg, universalLinksOnly: universalLinksOnlyArg) { result in
          switch result {
          case .success(let res):
            reply(wrapResult(res))
          case .failure(let error):
            reply(wrapError(error))
          }
        }
      }
    } else {
      launchUrlChannel.setMessageHandler(nil)
    }
    /// Opens the URL in an in-app SFSafariViewController, returning the results
    /// of loading it.
    let openUrlInSafariViewControllerChannel = FlutterBasicMessageChannel(
      name:
        "dev.flutter.pigeon.url_launcher_ios.UrlLauncherApi.openUrlInSafariViewController\(channelSuffix)",
      binaryMessenger: binaryMessenger, codec: codec)
    if let api = api {
      openUrlInSafariViewControllerChannel.setMessageHandler { message, reply in
        let args = message as! [Any?]
        let urlArg = args[0] as! String
        api.openUrlInSafariViewController(url: urlArg) { result in
          switch result {
          case .success(let res):
            reply(wrapResult(res))
          case .failure(let error):
            reply(wrapError(error))
          }
        }
      }
    } else {
      openUrlInSafariViewControllerChannel.setMessageHandler(nil)
    }
    /// Closes the view controller opened by [openUrlInSafariViewController].
    let closeSafariViewControllerChannel = FlutterBasicMessageChannel(
      name:
        "dev.flutter.pigeon.url_launcher_ios.UrlLauncherApi.closeSafariViewController\(channelSuffix)",
      binaryMessenger: binaryMessenger, codec: codec)
    if let api = api {
      closeSafariViewControllerChannel.setMessageHandler { _, reply in
        do {
          try api.closeSafariViewController()
          reply(wrapResult(nil))
        } catch {
          reply(wrapError(error))
        }
      }
    } else {
      closeSafariViewControllerChannel.setMessageHandler(nil)
    }
  }
}
