import AppKit
import CommanderCore

/// Colori presi dal Total Commander di Paolo: sfondo nero, testo bianco, cursore rosso.
enum Theme {
    static let background = NSColor.black
    static let text = NSColor.white
    static let hiddenText = NSColor(white: 0.55, alpha: 1)
    static let markedText = NSColor(srgbRed: 1, green: 0.85, blue: 0.1, alpha: 1)
    static let cursorActive = NSColor(srgbRed: 0.80, green: 0.05, blue: 0.05, alpha: 1)
    static let cursorInactive = NSColor(white: 0.45, alpha: 1)
    static let filterText = NSColor(srgbRed: 1, green: 0.85, blue: 0.1, alpha: 1)
    static let font = NSFont.systemFont(ofSize: 13)
    static let digits = NSFont.monospacedDigitSystemFont(ofSize: 13, weight: .regular)
    static let small = NSFont.systemFont(ofSize: 11)
    static let rowHeight: CGFloat = 20
}

/// Pulsante con un'azione in closure.
final class ActionButton: NSButton {
    private var handler: (() -> Void)?

    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" della finestra di copia aperta, se c'è.
    static weak var queueButton: NSButton?

    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 }
        }
        let r = a.runModal()
        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.runModal() == .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.runModal()
    }

    static func conflict(destination: URL, source: URL) -> ConflictChoice {
        func describe(_ u: URL) -> String {
            let v = try? u.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey, .isDirectoryKey])
            if v?.isDirectory == true { return "cartella, \(Format.date(v?.contentModificationDate))" }
            return "\(Format.bytes(Int64(v?.fileSize ?? 0))) byte, \(Format.date(v?.contentModificationDate))"
        }
        let a = NSAlert()
        a.messageText = "\"\(destination.lastPathComponent)\" esiste già"
        a.informativeText = "In: \(Format.path(destination.deletingLastPathComponent()))\n\nNuovo:      \(describe(source))\nEsistente: \(describe(destination))"
        a.addButton(withTitle: "Sovrascrivi")
        a.addButton(withTitle: "Sovrascrivi tutti")
        a.addButton(withTitle: "Salta")
        a.addButton(withTitle: "Salta tutti")
        let c = a.addButton(withTitle: "Annulla")
        c.keyEquivalent = "\u{1b}"
        switch a.runModal().rawValue - NSApplication.ModalResponse.alertFirstButtonReturn.rawValue {
        case 0: return .overwrite
        case 1: return .overwriteAll
        case 2: return .skip
        case 3: return .skipAll
        default: return .cancel
        }
    }

    static func error(_ error: Error, at url: URL) -> ErrorChoice {
        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.runModal() == .alertFirstButtonReturn ? .skip : .cancel
    }

    static func trashFailed(_ url: URL, error: Error) -> TrashFallback {
        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.runModal().rawValue - NSApplication.ModalResponse.alertFirstButtonReturn.rawValue {
        case 0: return .deletePermanently
        case 1: return .deleteAllPermanently
        case 2: return .skip
        default: return .cancel
        }
    }
}
