import AppKit
import ServiceManagement

class AppDelegate: NSObject, NSApplicationDelegate {
    // MARK: - State
    private var aboutWindow:  MenulessWindow!

    // MARK: - Lifecycle
    func applicationDidFinishLaunching(_ notification: Notification) {
        setupAboutWindow()
        setupNotifications()

        CmdManager.standard.configure()
    }

    func applicationWillTerminate(_ notification: Notification) {
        persistMenuBar(false)
        CmdManager.standard.clearItems()
    }

    // MARK: - Notifications
    private func setupNotifications() {
        NSWorkspace.shared.notificationCenter
            .addObserver(self, selector: #selector(wakeUp),
                         name: NSWorkspace.didWakeNotification,
                         object: nil)
    }

    @objc private func wakeUp() {
        CmdManager.standard.resetTimers()
    }

    // MARK: - Status Items
    @objc func reloadWidgets() {
        CmdManager.standard.reloadItems()
    }

    @objc func terminateApp() {
        DispatchQueue.main.async {
            NSApplication.shared.terminate(self)
        }
    }

    // MARK: - Setup About Window
    private func setupAboutWindow() {
        aboutWindow = MenulessWindow(viewController: AboutViewController())
        aboutWindow.level = .statusBar
    }

    // MARK: - Show About Window
    @objc func showAbout() {
        NSApplication.shared.activate(ignoringOtherApps: true)
        aboutWindow.makeKeyAndOrderFront(nil)
    }

    // MARK: - Launch at Login
    func toggleLaunchAtLogin() {
        let service = SMAppService.mainApp
        if service.status == .enabled {
            try? service.unregister()
        } else {
            try? service.register()
        }
    }
}
