import AppKit
import CommanderCore

/// Colori presi dal Total Commander di Paolo: sfondo nero, testo bianco,
/// selezionati in rosso, cursore = cornice rossa (solo nel pannello attivo).
/// I colori e la dimensione del testo si cambiano nelle Impostazioni (Cmd+,).
enum Theme {
    static var background: NSColor { Settings.shared.color(.background) }
    static var background2: NSColor { Settings.shared.color(.background2) }
    static var text: NSColor { Settings.shared.color(.text) }
    static var hiddenText: NSColor { Settings.shared.color(.hidden) }
    static var markedText: NSColor { Settings.shared.color(.marked) }
    static var cursor: NSColor { Settings.shared.color(.cursor) }
    static var cursorText: NSColor { Settings.shared.color(.cursorText) }
    static var pathBarActive: NSColor { Settings.shared.color(.pathBar) }
    static var pathBarInactive: NSColor { Settings.shared.isDark ? NSColor(white: 0.20, alpha: 1) : NSColor(white: 0.86, alpha: 1) }
    static var panelDivider: NSColor { Settings.shared.isDark ? NSColor(white: 0.25, alpha: 1) : NSColor(white: 0.75, alpha: 1) }
    static var filterText: NSColor {
        Settings.shared.isDark ? NSColor(srgbRed: 1, green: 0.85, blue: 0.1, alpha: 1) : NSColor(srgbRed: 0.62, green: 0.36, blue: 0, alpha: 1)
    }
    static var font: NSFont { NSFont.systemFont(ofSize: Settings.shared.fontSize, weight: .medium) }
    static var digits: NSFont { NSFont.monospacedDigitSystemFont(ofSize: Settings.shared.fontSize, weight: .medium) }
    static let small = NSFont.systemFont(ofSize: 11)
    static var rowHeight: CGFloat { (Settings.shared.fontSize * 1.54).rounded() }
}

/// Finestre e avvisi si aprono al centro della finestra principale, non dello schermo.
enum AppWindow {
    weak static var main: NSWindow?
}

extension NSWindow {
    func centerInApp() {
        guard let m = AppWindow.main, m !== self, m.isVisible, !m.isMiniaturized else { center(); return }
        let f = m.frame
        var origin = NSPoint(x: (f.midX - frame.width / 2).rounded(), y: (f.midY - frame.height / 2).rounded())
        if let v = m.screen?.visibleFrame {
            origin.x = min(max(origin.x, v.minX), v.maxX - frame.width)
            origin.y = min(max(origin.y, v.minY), v.maxY - frame.height)
        }
        setFrameOrigin(origin)
    }
}

extension NSAlert {
    /// runModal() mette l'avviso al centro dello schermo: appena parte lo si sposta al centro dell'app.
    @discardableResult
    func runCentered() -> NSApplication.ModalResponse {
        RunLoop.main.perform(inModes: [.modalPanel]) { [weak self] in self?.window.centerInApp() }
        ButtonNavigator.begin(window)
        defer { ButtonNavigator.end(window) }
        return runModal()
    }
}

/// Negli avvisi del Mac (NSAlert) i pulsanti si raggiungono con la tastiera solo se è attiva
/// "Navigazione da tastiera" nelle Impostazioni di Sistema. Qui funziona sempre, come su Windows:
/// Tab / Shift+Tab e le frecce passano da un pulsante all'altro (con una cornice blu),
/// Invio o Spazio premono quello evidenziato. Senza muoversi, Invio preme il pulsante blu ed Esc annulla.
enum ButtonNavigator {
    private final class State {
        weak var window: NSWindow?
        var index: Int?
        weak var highlighted: NSButton?
        init(_ w: NSWindow) { window = w }
    }
    private static var stack: [State] = []

    static func begin(_ w: NSWindow) { stack.append(State(w)) }

    static func end(_ w: NSWindow) {
        guard let i = stack.lastIndex(where: { $0.window === w }) else { return }
        show(nil, in: stack[i])
        stack.remove(at: i)
    }

    /// Dall'osservatore dei tasti, quando c'è un avviso aperto.
    static func handle(_ e: NSEvent) -> Bool {
        guard let st = stack.last, let w = st.window, NSApp.modalWindow === w else { return false }
        let buttons = pushButtons(in: w)
        guard buttons.count > 1 else { return false }
        let mods = e.modifierFlags.intersection([.control, .option, .command, .shift])
        let editing = w.firstResponder is NSTextView
        let current = st.index ?? buttons.firstIndex(where: { $0.keyEquivalent == "\r" }) ?? 0
        // Si parte dal pulsante blu: il primo Tab va al successivo, come su Windows.
        func move(_ d: Int) {
            let n = buttons.count
            let i = ((current + d) % n + n) % n
            st.index = i
            show(buttons[i], in: st)
        }
        switch e.keyCode {
        case KeyCode.tab where mods.isEmpty || mods == .shift:
            move(mods == .shift ? -1 : 1)
            return true
        case KeyCode.down, KeyCode.right, KeyCode.up, KeyCode.left:
            guard mods.isEmpty, !editing else { return false }
            move(e.keyCode == KeyCode.down || e.keyCode == KeyCode.right ? 1 : -1)
            return true
        case KeyCode.returnKey, KeyCode.keypadEnter, KeyCode.space:
            guard mods.isEmpty, let b = st.highlighted, !(editing && e.keyCode == KeyCode.space) else { return false }
            b.performClick(nil)
            return true
        default:
            return false
        }
    }

    /// I pulsanti dell'avviso, dall'alto in basso e da sinistra a destra (le caselle restano fuori).
    private static func pushButtons(in w: NSWindow) -> [NSButton] {
        var out: [NSButton] = []
        func walk(_ v: NSView) {
            for s in v.subviews {
                if let b = s as? NSButton, b.bezelStyle == .push, b.isEnabled, !b.isHiddenOrHasHiddenAncestor { out.append(b) }
                walk(s)
            }
        }
        if let c = w.contentView { walk(c) }
        return out.sorted {
            let a = $0.convert($0.bounds, to: nil), b = $1.convert($1.bounds, to: nil)
            return abs(a.midY - b.midY) > 4 ? a.midY > b.midY : a.minX < b.minX
        }
    }

    private static func show(_ b: NSButton?, in st: State) {
        if let old = st.highlighted { old.layer?.borderWidth = 0 }
        st.highlighted = b
        guard let b else { return }
        b.wantsLayer = true
        b.layer?.cornerRadius = b.bounds.height / 2
        b.layer?.borderWidth = 2.5
        b.layer?.borderColor = NSColor.keyboardFocusIndicatorColor.withAlphaComponent(1).cgColor
    }
}

/// Pulsante con un'azione in closure.
final class ActionButton: NSButton {
    private var handler: (() -> Void)?
    /// Raggiungibile con Tab come su Windows, anche senza "Navigazione da tastiera" attiva nel Mac.
    var tabStop = false

    override var canBecomeKeyView: Bool { tabStop || super.canBecomeKeyView }
    override var acceptsFirstResponder: Bool { tabStop || super.acceptsFirstResponder }

    // Il pulsante raggiunto con Tab ha una cornice ben visibile (il Mac di solito non la mostra).
    override func becomeFirstResponder() -> Bool {
        let ok = super.becomeFirstResponder()
        if ok && tabStop { showFocus(true) }
        return ok
    }

    override func resignFirstResponder() -> Bool {
        let ok = super.resignFirstResponder()
        if ok { showFocus(false) }
        return ok
    }

    private func showFocus(_ on: Bool) {
        wantsLayer = true
        layer?.cornerRadius = 6
        layer?.borderWidth = on ? 2.5 : 0
        layer?.borderColor = NSColor.keyboardFocusIndicatorColor.withAlphaComponent(1).cgColor
    }

    convenience init(_ title: String, handler: @escaping () -> Void) {
        self.init(title: title, target: nil, action: nil)
        self.handler = handler
        target = self
        action = #selector(fire)
    }

    @objc private func fire() { handler?() }
}

/// Voce di menu con un'azione in closure.
final class ActionMenuItem: NSMenuItem {
    private var handler: (() -> Void)?

    convenience init(_ title: String, key: String = "", handler: @escaping () -> Void) {
        self.init(title: title, action: #selector(fire), keyEquivalent: key)
        keyEquivalentModifierMask = []
        self.handler = handler
        target = self
    }

    @objc private func fire() { handler?() }
}

/// Osserva una cartella e avvisa quando cambia (sui dischi di rete spesso non arriva niente: c'è Ctrl+R).
final class DirectoryWatcher {
    private var source: DispatchSourceFileSystemObject?

    init?(url: URL, handler: @escaping () -> Void) {
        let fd = open(url.path, O_EVTONLY)
        guard fd >= 0 else { return nil }
        let s = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fd, eventMask: [.write, .delete, .rename, .link], queue: .main)
        s.setEventHandler(handler: handler)
        s.setCancelHandler { close(fd) }
        s.resume()
        source = s
    }

    deinit { source?.cancel() }
}

enum Dialogs {
    /// Il pulsante "F2 Accoda" di una finestra di domanda aperta, se c'è.
    static weak var queueButton: NSButton?
    /// Tasti speciali della finestra modale aperta (F2, F7, lettere dei pulsanti).
    static var modalKeyHandler: ((NSEvent) -> Bool)?

    enum PromptResult { case ok(String), queue(String), cancel }

    /// Finestra con un campo di testo. Invio = OK, Esc = Annulla, F2 = Accoda (se c'è).
    static func prompt(_ title: String, info: String = "", value: String, okTitle: String = "OK",
                       queueTitle: String? = nil, selection: NSRange? = nil) -> PromptResult {
        let a = NSAlert()
        a.messageText = title
        a.informativeText = info
        a.addButton(withTitle: okTitle)
        if let queueTitle { queueButton = a.addButton(withTitle: queueTitle) }
        let cancel = a.addButton(withTitle: "Annulla")
        cancel.keyEquivalent = "\u{1b}"
        let tf = NSTextField(frame: NSRect(x: 0, y: 0, width: 520, height: 24))
        tf.stringValue = value
        tf.font = Theme.font
        tf.cell?.isScrollable = true
        tf.cell?.wraps = false
        a.accessoryView = tf
        a.layout()
        a.window.initialFirstResponder = tf
        DispatchQueue.main.async {
            a.window.makeFirstResponder(tf)
            if let selection, let ed = tf.currentEditor() { ed.selectedRange = selection }
        }
        // Le lettere devono finire nel campo, non nei pulsanti della finestra sotto.
        let previousHandler = modalKeyHandler
        modalKeyHandler = nil
        let r = a.runCentered()
        modalKeyHandler = previousHandler
        queueButton = nil
        switch r {
        case .alertFirstButtonReturn: return .ok(tf.stringValue)
        case .alertSecondButtonReturn where queueTitle != nil: return .queue(tf.stringValue)
        default: return .cancel
        }
    }

    static func confirm(_ title: String, info: String = "", ok: String) -> Bool {
        let a = NSAlert()
        a.messageText = title
        a.informativeText = info
        a.addButton(withTitle: ok)
        let c = a.addButton(withTitle: "Annulla")
        c.keyEquivalent = "\u{1b}"
        return a.runCentered() == .alertFirstButtonReturn
    }

    static func message(_ title: String, info: String = "", style: NSAlert.Style = .informational) {
        let a = NSAlert()
        a.alertStyle = style
        a.messageText = title
        a.informativeText = info
        a.addButton(withTitle: "OK")
        a.runCentered()
    }

    /// Le domande che arrivano dalla coda possono comparire mentre si usa un'altra app.
    static func bringForward() {
        if !NSApp.isActive {
            NSApp.requestUserAttention(.criticalRequest)
            NSApp.activate(ignoringOtherApps: true)
        }
    }

    static func error(_ error: Error, at url: URL) -> ErrorChoice {
        bringForward()
        let a = NSAlert()
        a.alertStyle = .warning
        a.messageText = "Errore con \"\(url.lastPathComponent)\""
        a.informativeText = error.localizedDescription
        a.addButton(withTitle: "Salta")
        let c = a.addButton(withTitle: "Annulla tutto")
        c.keyEquivalent = "\u{1b}"
        return a.runCentered() == .alertFirstButtonReturn ? .skip : .cancel
    }

    static func trashFailed(_ url: URL, error: Error) -> TrashFallback {
        bringForward()
        let a = NSAlert()
        a.alertStyle = .warning
        a.messageText = "Non posso mettere \"\(url.lastPathComponent)\" nel Cestino"
        a.informativeText = "Su questo disco il Cestino non c'è (succede con il NAS). Lo elimino definitivamente?\n\n\(error.localizedDescription)"
        a.addButton(withTitle: "Elimina")
        a.addButton(withTitle: "Elimina tutti")
        a.addButton(withTitle: "Salta")
        let c = a.addButton(withTitle: "Annulla")
        c.keyEquivalent = "\u{1b}"
        switch a.runCentered().rawValue - NSApplication.ModalResponse.alertFirstButtonReturn.rawValue {
        case 0: return .deletePermanently
        case 1: return .deleteAllPermanently
        case 2: return .skip
        default: return .cancel
        }
    }
}

extension String {
    /// "1 file" -> "1 file", "«a»" resta uguale, "due file" -> "Due file".
    var capitalizedFirst: String { prefix(1).uppercased() + dropFirst() }
}
