import AppKit

/// Comandi dell'app. I nomi seguono quelli di Total Commander (cm_...).
enum Command {
    // Movimento
    case up, down, pageUp, pageDown, home, end
    case markUp, markDown
    case open, parentOrFilterBack, goParent, enterPackage, goRoot
    case switchPanel, escape
    // Pannelli, schede, cronologia
    case transferLeft, transferRight, openInNewTab, openInOtherNewTab
    case historyBack, historyForward, historyList
    case locationLeft, locationRight, hotlist
    case newTab, newTabBackground, closeTab, closeAllTabs, nextTab, prevTab, tabList
    case swapPanels, reread
    // File
    case view, edit, newTextFile, copy, copySameDir, move, renameInPlace, mkdir
    case delete, deletePermanent, calcSize
    case clipCopy, clipCut, clipPaste
    // Selezione
    case space, insertMark, selectMask, deselectMask, invertSelection, restoreSelection
    case selectAll, deselectAll, selectSameExt, deselectSameExt
    case quit
}

enum KeyCode {
    static let f1: UInt16 = 122, f2: UInt16 = 120, f3: UInt16 = 99, f4: UInt16 = 118
    static let f5: UInt16 = 96, f6: UInt16 = 97, f7: UInt16 = 98, f8: UInt16 = 100
    static let left: UInt16 = 123, right: UInt16 = 124, down: UInt16 = 125, up: UInt16 = 126
    static let returnKey: UInt16 = 36, keypadEnter: UInt16 = 76, tab: UInt16 = 48, space: UInt16 = 49
    static let backspace: UInt16 = 51, forwardDelete: UInt16 = 117, escape: UInt16 = 53
    static let home: UInt16 = 115, end: UInt16 = 119, pageUp: UInt16 = 116, pageDown: UInt16 = 121
    static let insert: UInt16 = 114
    static let keypadPlus: UInt16 = 69, keypadMinus: UInt16 = 78, keypadMultiply: UInt16 = 67, keypadDivide: UInt16 = 75
    static let isoSection: UInt16 = 10, isoAngle: UInt16 = 50   // "\" e "<" sulla tastiera italiana
}

/// Modificatori come in TC: Ctrl resta Ctrl, Alt diventa Option.
struct Mods: OptionSet, Hashable {
    let rawValue: UInt8
    static let ctrl = Mods(rawValue: 1)
    static let opt = Mods(rawValue: 2)
    static let shift = Mods(rawValue: 4)
    static let none: Mods = []

    init(rawValue: UInt8) { self.rawValue = rawValue }

    init(_ flags: NSEvent.ModifierFlags) {
        var m: Mods = []
        if flags.contains(.control) { m.insert(.ctrl) }
        if flags.contains(.option) { m.insert(.opt) }
        if flags.contains(.shift) { m.insert(.shift) }
        self = m
    }
}

enum KeyMap {
    private struct Combo: Hashable {
        let key: String
        let mods: Mods
    }

    private static func code(_ c: UInt16, _ m: Mods = .none) -> Combo { Combo(key: "k\(c)", mods: m) }
    private static func char(_ s: String, _ m: Mods = .none) -> Combo { Combo(key: "c\(s)", mods: m) }

    private static let table: [Combo: Command] = {
        var t: [Combo: Command] = [:]
        // Tasti funzione
        t[code(KeyCode.f1, .opt)] = .locationLeft
        t[code(KeyCode.f2)] = .reread
        t[code(KeyCode.f2, .opt)] = .locationRight
        t[code(KeyCode.f3)] = .view
        t[code(KeyCode.f3, .shift)] = .view
        t[code(KeyCode.f4)] = .edit
        t[code(KeyCode.f4, .shift)] = .newTextFile
        t[code(KeyCode.f4, .opt)] = .quit
        t[code(KeyCode.f5)] = .copy
        t[code(KeyCode.f5, .shift)] = .copySameDir
        t[code(KeyCode.f6)] = .move
        t[code(KeyCode.f6, .shift)] = .renameInPlace
        t[code(KeyCode.f7)] = .mkdir
        t[code(KeyCode.f8)] = .delete
        t[code(KeyCode.f8, .shift)] = .deletePermanent
        t[code(KeyCode.forwardDelete)] = .delete
        t[code(KeyCode.forwardDelete, .shift)] = .deletePermanent
        // Movimento
        t[code(KeyCode.up)] = .up
        t[code(KeyCode.down)] = .down
        t[code(KeyCode.up, .shift)] = .markUp
        t[code(KeyCode.down, .shift)] = .markDown
        t[code(KeyCode.pageUp)] = .pageUp
        t[code(KeyCode.pageDown)] = .pageDown
        t[code(KeyCode.home)] = .home
        t[code(KeyCode.end)] = .end
        t[code(KeyCode.returnKey)] = .open
        t[code(KeyCode.keypadEnter)] = .open
        t[code(KeyCode.returnKey, .shift)] = .open
        t[code(KeyCode.backspace)] = .parentOrFilterBack
        t[code(KeyCode.pageUp, .ctrl)] = .goParent
        t[code(KeyCode.pageDown, .ctrl)] = .enterPackage
        t[code(KeyCode.isoSection, .ctrl)] = .goRoot
        t[code(KeyCode.isoAngle, .ctrl)] = .goRoot
        t[char("\\", .ctrl)] = .goRoot
        t[char("<", .ctrl)] = .goRoot
        t[code(KeyCode.tab)] = .switchPanel
        t[code(KeyCode.escape)] = .escape
        // Ctrl e Option con le frecce
        t[code(KeyCode.left, .ctrl)] = .transferLeft
        t[code(KeyCode.right, .ctrl)] = .transferRight
        t[code(KeyCode.up, .ctrl)] = .openInNewTab
        t[code(KeyCode.up, [.ctrl, .shift])] = .openInOtherNewTab
        t[code(KeyCode.left, .opt)] = .historyBack
        t[code(KeyCode.right, .opt)] = .historyForward
        t[code(KeyCode.down, .opt)] = .historyList
        // Schede
        t[code(KeyCode.tab, .ctrl)] = .nextTab
        t[code(KeyCode.tab, [.ctrl, .shift])] = .prevTab
        t[char("t", .ctrl)] = .newTab
        t[char("t", [.ctrl, .shift])] = .newTabBackground
        t[char("w", .ctrl)] = .closeTab
        t[char("w", [.ctrl, .shift])] = .closeAllTabs
        t[char("a", [.ctrl, .shift])] = .tabList
        // Ctrl+lettera
        t[char("a", .ctrl)] = .selectAll
        t[char("c", .ctrl)] = .clipCopy
        t[char("x", .ctrl)] = .clipCut
        t[char("v", .ctrl)] = .clipPaste
        t[char("d", .ctrl)] = .hotlist
        t[char("l", .ctrl)] = .calcSize
        t[char("r", .ctrl)] = .reread
        t[char("u", .ctrl)] = .swapPanels
        // Selezione: tastierino numerico
        t[code(KeyCode.space)] = .space
        t[code(KeyCode.insert)] = .insertMark
        t[code(KeyCode.keypadPlus)] = .selectMask
        t[code(KeyCode.keypadPlus, .shift)] = .selectMask
        t[code(KeyCode.keypadPlus, .ctrl)] = .selectAll
        t[code(KeyCode.keypadPlus, [.ctrl, .shift])] = .selectAll
        t[code(KeyCode.keypadPlus, .opt)] = .selectSameExt
        t[code(KeyCode.keypadMinus)] = .deselectMask
        t[code(KeyCode.keypadMinus, .shift)] = .deselectMask
        t[code(KeyCode.keypadMinus, .ctrl)] = .deselectAll
        t[code(KeyCode.keypadMinus, [.ctrl, .shift])] = .deselectAll
        t[code(KeyCode.keypadMinus, .opt)] = .deselectSameExt
        t[code(KeyCode.keypadMultiply)] = .invertSelection
        t[code(KeyCode.keypadMultiply, .shift)] = .invertSelection
        t[code(KeyCode.keypadDivide)] = .restoreSelection
        return t
    }()

    /// + - * della tastiera normale, al posto del tastierino del MacBook.
    /// Valgono solo quando non si sta scrivendo nella ricerca rapida.
    private static let mainKeyboardSelection: [Combo: Command] = [
        char("+"): .selectMask,
        char("+", .ctrl): .selectAll,
        char("+", .opt): .selectSameExt,
        char("-"): .deselectMask,
        char("-", .ctrl): .deselectAll,
        char("-", .opt): .deselectSameExt,
        char("*"): .invertSelection,
    ]

    static func command(for e: NSEvent, quickSearchActive: Bool) -> Command? {
        let mods = Mods(e.modifierFlags)
        if let c = table[code(e.keyCode, mods)] { return c }
        guard let raw = e.charactersIgnoringModifiers, !raw.isEmpty else { return nil }
        let ch = raw.lowercased()
        let isLetter = ch.unicodeScalars.allSatisfy { CharacterSet.letters.contains($0) }
        // Per i simboli lo Shift fa parte del carattere ("*" è Shift + "+").
        let m = isLetter ? mods : mods.subtracting(.shift)
        if let c = table[char(ch, m)] { return c }
        if !quickSearchActive || !m.isEmpty, let c = mainKeyboardSelection[char(ch, m)] {
            // Fuori dal tastierino: Option produce altri caratteri, si guarda il tasto.
            return c
        }
        return nil
    }
}
