//
//  TuskerSceneDelegate.swift
//  Tusker
//
//  Created by Shadowfacts on 10/31/22.
//  Copyright © 2022 Shadowfacts. All rights reserved.
//

import UIKit
import Sentry

protocol TuskerSceneDelegate: UISceneDelegate {
    var window: UIWindow? { get }
    var rootViewController: TuskerRootViewController? { get }
}

enum StatusBarTapActionResult {
    case `continue`
    case stop
}

extension TuskerSceneDelegate {
    func handleStatusBarTapped(xPosition: CGFloat) -> StatusBarTapActionResult {
        if let rootViewController {
            let converted = rootViewController.view.convert(CGPoint(x: xPosition, y: 0), from: nil)
            return rootViewController.handleStatusBarTapped(xPosition: converted.x)
        }
        return .continue
    }
    
    func applyAppearancePreferences() {
        guard let window else { return }
        window.overrideUserInterfaceStyle = Preferences.shared.theme
        window.tintColor = Preferences.shared.accentColor.color
        if #available(iOS 17.0, *) {
            window.traitOverrides.pureBlackDarkMode = Preferences.shared.pureBlackDarkMode
        } else {
            let exception = catchNSException {
                let key = ["Controller", "Presentation", "root", "_"].reversed().joined()
                if let rootPresentationController = window.value(forKey: key) as? UIPresentationController {
                    rootPresentationController.overrideTraitCollection = UITraitCollection(pureBlackDarkMode: Preferences.shared.pureBlackDarkMode)
                }
            }
            if let exception {
                SentrySDK.capture(exception: exception)
            }
        }
    }
}
