import Foundation
import UIKit
import React

@objc(ScreenOrientation)
class ScreenOrientation: NSObject {

  @objc static func requiresMainQueueSetup() -> Bool {
    return true
  }

  private func updateSupportedOrientations() {
    DispatchQueue.main.async {
      if #available(iOS 16.0, *) {
        if let rootViewController = UIApplication.shared.delegate?.window??.rootViewController {
          rootViewController.setNeedsUpdateOfSupportedInterfaceOrientations()
        }
      }
    }
  }

  @objc func setPortrait() {
    DispatchQueue.main.async {
      self.updateSupportedOrientations()

      if #available(iOS 16.0, *) {
        guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene else {
          print("[ScreenOrientation] Failed to get UIWindowScene")
          return
        }
        let geometryPreferences = UIWindowScene.GeometryPreferences.iOS(interfaceOrientations: .portrait)
        windowScene.requestGeometryUpdate(geometryPreferences) { error in
          print(error)
        }
      } else {
        UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation")
        UIViewController.attemptRotationToDeviceOrientation()
      }
    }
  }

  @objc func setLandscape() {
    DispatchQueue.main.async {
      self.updateSupportedOrientations()

      if #available(iOS 16.0, *) {
        guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene else {
          print("[ScreenOrientation] Failed to get UIWindowScene")
          return
        }
        let geometryPreferences = UIWindowScene.GeometryPreferences.iOS(interfaceOrientations: .landscapeRight)
        windowScene.requestGeometryUpdate(geometryPreferences) { error in
          print(error)
        }
      } else {
        UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation")
        UIViewController.attemptRotationToDeviceOrientation()
      }
    }
  }
}
