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

import UIKit

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
    {
        return true
    }

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration
    {
        if let userActivity = options.userActivities.first {
            if userActivity.activityType == SessionActivityType.SettingsWindow.rawValue {
                return UISceneConfiguration(name: "Settings", sessionRole: connectingSceneSession.role)
            }
            
            if userActivity.activityType == SessionActivityType.ReaderWindow.rawValue {
                return UISceneConfiguration(name: "Reader", sessionRole: connectingSceneSession.role)
            }
        }
        
        return UISceneConfiguration(name: "Browser", sessionRole: connectingSceneSession.role)
    }
    
    private func historyMenu() -> UIMenu {
        let historyItems = BrowserHistory.shared.allHistory(limit: 50).map { item in
            let title = ((item.title.count > 0) ? item.title : item.url.absoluteString)
                .middleTruncatedString(maximumLength: 85)
            
            return UIAction(title: title) { action in
                UIApplication.shared.sendAction(#selector(ShortcutResponder.handleOpenURL), to: nil, from: action, for: OpenURLEvent(url: item.url))
            }
        }
        
        return UIMenu(title: "History", children: [
            UIKeyCommand(
                modifiers: [ .command ],
                input: "y",
                title: "Show All History…",
                action: #selector(ShortcutResponder.showHistory)
            ),
            
            UIMenu(options: .displayInline, children: historyItems)
        ])
    }
    
    override var keyCommands: [UIKeyCommand]? {
        get { KeyboardShortcuts.allKeyCommands() }
    }
    
    override func buildMenu(with builder: UIMenuBuilder) {
        // File
        builder.replaceChildren(ofMenu: .file) { children in
            return KeyboardShortcuts.menu(for: .file) + children
        }
        
        // X Format X
        builder.remove(menu: .format)
        
        // Application
        builder.replaceChildren(ofMenu: .application, from: { children in
            let index = children.firstIndex(where: { elem in
                if let elem = elem as? UIMenu {
                    return elem.identifier == .about
                }
                return false
            })
            
            var newChildren = children
            let shortcuts = KeyboardShortcuts.menu(for: .application)
            if let index = index {
                newChildren.insert(contentsOf: shortcuts, at: index + 1)
            } else {
                newChildren.append(contentsOf: shortcuts)
            }
            
            return newChildren
        })
        
        // Go
        builder.insertSibling(UIMenu(title: "Go", children: KeyboardShortcuts.menu(for: .go)), beforeMenu: .view)
        
        // History
        builder.insertSibling(historyMenu(), beforeMenu: .view)
        
        // View
        builder.replaceChildren(ofMenu: .view) { children in
            KeyboardShortcuts.menu(for: .view) + children
        }
    }
}

