//
//  ReaderSceneDelegate.swift
//  App
//
//  Created by James Magahern on 8/22/22.
//

import UIKit

internal enum ReaderUserActivityKeys: String {
    case htmlString
    case baseURL
}

class ReaderSceneDelegate: UIResponder, UIWindowSceneDelegate {
    var window: UIWindow?
    var readerViewController: ReaderViewController?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions)
    {
        guard let windowScene = (scene as? UIWindowScene) else { return }
        guard let activity = connectionOptions.userActivities.first else { return }
        
        guard let userInfo = activity.userInfo, let htmlString: String = userInfo[ReaderUserActivityKeys.htmlString.rawValue] as? String else { return }
        let baseURL = userInfo[ReaderUserActivityKeys.baseURL.rawValue] as? URL
        
        let window = UIWindow(windowScene: windowScene)
        
        let readerViewController = ReaderViewController(readableHTMLString: htmlString, baseURL: baseURL)
        readerViewController.title = activity.title
        
        self.readerViewController = readerViewController
        window.rootViewController = UINavigationController(rootViewController: readerViewController)
        
        windowScene.title = activity.title ?? "Reader"
        windowScene.sizeRestrictions?.maximumSize = CGSize(width: 700.0, height: 1000.0)
        
        window.makeKeyAndVisible()
        self.window = window
    }
}
