//
//  BrowserSceneDelegate.swift
//  SBrowser
//
//  Created by James Magahern on 7/21/20.
//

import UIKit

public enum SessionActivityType: String {
    case BrowserWindow  = "net.buzzert.attractor.browser"
    case SettingsWindow = "net.buzzert.attractor.settings"
    case ReaderWindow   = "net.buzzert.attractor.reader"
}

class BrowserSceneDelegate: UIResponder, UIWindowSceneDelegate {
    var window: UIWindow?
    
    var browserViewController: BrowserViewController?
    var settingsViewController: SettingsViewController?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions)
    {
        guard let windowScene = (scene as? UIWindowScene) else { return }
        
        let window = UIWindow(windowScene: windowScene)
        let browserViewController = BrowserViewController()
        self.browserViewController = browserViewController
        window.rootViewController = browserViewController
        
        if let urlContext = connectionOptions.urlContexts.first {
            let url = urlContext.url
            browserViewController.currentTab.beginLoadingURL(url)
        }
        
#if targetEnvironment(macCatalyst)
        windowScene.titlebar?.titleVisibility = .hidden
        windowScene.titlebar?.separatorStyle = .none
            
        if #available(macCatalyst 16.0, *) {
            let screenSize = windowScene.screen.bounds.size
            let preferredSize = CGSize(width: 1000, height: 1100)
            let geometryPreferences = UIWindowScene.GeometryPreferences.Mac(systemFrame: CGRect(
                origin: CGPoint(
                    x: (screenSize.width - preferredSize.width) / 2,
                    y: (screenSize.height - preferredSize.height) / 2
                ),
                
                size: preferredSize
            ))
            windowScene.requestGeometryUpdate(geometryPreferences)
        }
#endif
        
        window.makeKeyAndVisible()
        self.window = window
    }
    
    func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>)
    {
        for urlContext in URLContexts {
            if browserViewController?.currentTab.url == nil {
                browserViewController?.currentTab.beginLoadingURL(urlContext.url)
            } else {
                browserViewController?.createNewTab(withURL: urlContext.url)
            }
        }
    }
}

