import AppKit
import CommanderCore

/// Tasto destro su file e cartelle: le voci del menu del Finder (Apri, Apri con, Cestino, Ottieni
/// informazioni, Rinomina, Comprimi, Duplica, Crea alias, Anteprima, Copia, Condividi, Tag, Mostra nel
/// Finder) e in fondo i Servizi e le Azioni rapide del Mac, che AppKit aggiunge da solo.
/// Il menu esatto del Finder non è a disposizione delle altre app: questo lo riproduce.
extension MainWindowController: NSMenuDelegate {
    func panelContextMenu(_ panel: FilePanel, items: [FileItem]) -> NSMenu? {
        let menu = NSMenu()
        menu.delegate = self
        menu.autoenablesItems = false
        func add(_ title: String, _ action: @escaping () -> Void) {
            menu.addItem(ActionMenuItem(title, handler: action))
        }
        let urls = items.map(\.url)
        let one = items.count == 1 ? items[0] : nil
        let what = one.map { "«\($0.name)»" } ?? "\(items.count) elementi"

        // Sul server FTP o dentro un archivio: si apre, si guarda e si copia fuori.
        if panel.isRemote || panel.isInArchive {
            guard !items.isEmpty else { return nil }
            add("Apri") { [weak self] in self?.perform(.open) }
            if one.map({ !$0.showsAsFolder }) ?? false {
                add("Anteprima di \(what)") { [weak self] in self?.toggleQuickLook() }
            }
            menu.addItem(.separator())
            add("Copia nell'altro pannello (F5)…") { [weak self] in self?.perform(.copy) }
            return menu
        }

        // Spazio vuoto: la cartella del pannello.
        if items.isEmpty {
            let dir = panel.currentURL
            add("Nuova cartella") { [weak self] in self?.makeDirectory() }
            if NSPasteboard.general.canReadObject(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) {
                add("Incolla") { [weak self] in self?.paste() }
            }
            menu.addItem(.separator())
            add("Ottieni informazioni") { Self.showInfo([dir]) }
            add("Mostra nel Finder") { NSWorkspace.shared.open(dir) }
            add("Apri nel Terminale") { [weak self] in self?.perform(.terminal) }
            add("Copia il percorso") { Self.copyPaths([dir]) }
            return menu
        }

        add("Apri") { [weak panel] in
            if one?.showsAsFolder ?? false || items.contains(where: { ArchivePath.isArchiveName($0.name) }) && items.count == 1 {
                panel?.open()
            } else {
                for u in urls { NSWorkspace.shared.open(u) }
            }
        }
        if let openWith = openWithMenu(urls) {
            let item = NSMenuItem(title: "Apri con", action: nil, keyEquivalent: "")
            item.submenu = openWith
            menu.addItem(item)
        }
        menu.addItem(.separator())
        add("Sposta nel Cestino") { [weak self] in self?.delete(permanent: false) }
        menu.addItem(.separator())
        add("Ottieni informazioni") { Self.showInfo(urls) }
        if one != nil { add("Rinomina") { panel.beginRename() } }
        add("Comprimi \(what)") { [weak self] in self?.compressLikeFinder(items, in: panel.currentURL) }
        if items.contains(where: { !$0.showsAsFolder && ArchivePath.isArchiveName($0.name) }) {
            add("Estrai…") { [weak self] in self?.unpack() }
        }
        add("Duplica") { [weak self] in self?.duplicate(items) }
        add("Crea alias") { [weak panel] in Self.makeAliases(urls); panel?.refresh() }
        if one.map({ !$0.showsAsFolder }) ?? false {
            add("Anteprima di \(what)") { [weak self] in self?.toggleQuickLook() }
        }
        menu.addItem(.separator())
        add("Copia") { [weak self] in self?.clipboard(cut: false) }
        add("Copia il percorso") { Self.copyPaths(urls) }
        add("Condividi…") { [weak panel] in
            guard let panel else { return }
            let row = panel.cursorRow
            let rect = row >= 0 ? panel.table.rect(ofRow: row) : panel.table.visibleRect
            NSSharingServicePicker(items: urls).show(relativeTo: rect, of: panel.table, preferredEdge: .maxY)
        }
        menu.addItem(.separator())
        menu.addItem(tagsItem(items, panel: panel))
        menu.addItem(.separator())
        add("Mostra nel Finder") { NSWorkspace.shared.activateFileViewerSelecting(urls) }
        return menu
    }

    func menuWillOpen(_ menu: NSMenu) { menuOpen = true }
    func menuDidClose(_ menu: NSMenu) { menuOpen = false }

    // MARK: - Apri con

    private func openWithMenu(_ urls: [URL]) -> NSMenu? {
        guard let first = urls.first else { return nil }
        let apps = NSWorkspace.shared.urlsForApplications(toOpen: first)
        let def = NSWorkspace.shared.urlForApplication(toOpen: first)
        let menu = NSMenu()
        func item(_ app: URL, suffix: String = "") -> NSMenuItem {
            let name = FileManager.default.displayName(atPath: app.path).replacingOccurrences(of: ".app", with: "")
            let i = ActionMenuItem(name + suffix) {
                NSWorkspace.shared.open(urls, withApplicationAt: app, configuration: NSWorkspace.OpenConfiguration())
            }
            let icon = NSWorkspace.shared.icon(forFile: app.path)
            icon.size = NSSize(width: 16, height: 16)
            i.image = icon
            return i
        }
        if let def {
            menu.addItem(item(def, suffix: " (predefinita)"))
            menu.addItem(.separator())
        }
        let others = apps.filter { $0 != def }
            .sorted { FileManager.default.displayName(atPath: $0.path).localizedStandardCompare(FileManager.default.displayName(atPath: $1.path)) == .orderedAscending }
        for a in others { menu.addItem(item(a)) }
        if !others.isEmpty { menu.addItem(.separator()) }
        menu.addItem(ActionMenuItem("Altro…") {
            let p = NSOpenPanel()
            p.directoryURL = URL(fileURLWithPath: "/Applications")
            p.allowedContentTypes = [.application]
            guard p.runModal() == .OK, let app = p.url else { return }
            NSWorkspace.shared.open(urls, withApplicationAt: app, configuration: NSWorkspace.OpenConfiguration())
        })
        return menu
    }

    // MARK: - Azioni come nel Finder

    /// "Ottieni informazioni": la finestra Info del Finder, una per elemento.
    static func showInfo(_ urls: [URL]) {
        let pb = NSPasteboard(name: NSPasteboard.Name("MacCommander.info"))
        pb.clearContents()
        pb.writeObjects(urls as [NSURL])
        pb.setPropertyList(urls.map(\.path), forType: NSPasteboard.PasteboardType("NSFilenamesPboardType"))
        if NSPerformService("Finder/Show Info", pb) { return }
        // Se il servizio del Finder non c'è: AppleScript (la prima volta macOS chiede il permesso).
        let list = urls.map { "POSIX file \"\($0.path.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" }
        let script = "tell application \"Finder\"\nactivate\nrepeat with f in {\(list.joined(separator: ", "))}\nopen information window of (f as alias)\nend repeat\nend tell"
        let p = Process()
        p.executableURL = URL(fileURLWithPath: "/usr/bin/osascript")
        p.arguments = ["-e", script]
        try? p.run()
    }

    static func copyPaths(_ urls: [URL]) {
        let pb = NSPasteboard.general
        pb.clearContents()
        pb.setString(urls.map(\.path).joined(separator: "\n"), forType: .string)
    }

    /// Come "Comprimi" del Finder: "nome.zip" (o "Archivio.zip" per più elementi) nella stessa cartella.
    private func compressLikeFinder(_ items: [FileItem], in dir: URL) {
        let base = items.count == 1 ? (items[0].showsAsFolder ? items[0].name : items[0].baseName) : "Archivio"
        var dest = dir.appendingPathComponent(base + ".zip")
        var n = 2
        while FileManager.default.fileExists(atPath: dest.path) {
            dest = dir.appendingPathComponent("\(base) \(n).zip")
            n += 1
        }
        queue.enqueue(TransferJob(kind: .pack, sources: items.map(\.url), destination: dest))
    }

    /// Come "Duplica" del Finder: "nome copia.ext", "nome copia 2.ext"…
    private func duplicate(_ items: [FileItem]) {
        for i in items {
            let dir = i.url.deletingLastPathComponent()
            let ext = i.showsAsFolder ? "" : i.ext
            let base = i.showsAsFolder ? i.name : i.baseName
            func name(_ k: Int) -> String { "\(base) copia\(k > 1 ? " \(k)" : "")" + (ext.isEmpty ? "" : ".\(ext)") }
            var k = 1
            while FileManager.default.fileExists(atPath: dir.appendingPathComponent(name(k)).path) { k += 1 }
            queue.enqueue(TransferJob(kind: .copy, sources: [i.url], destination: dir, newName: name(k)))
        }
    }

    /// "Crea alias": un alias del Finder accanto all'originale ("nome alias").
    static func makeAliases(_ urls: [URL]) {
        for u in urls {
            do {
                let data = try u.bookmarkData(options: .suitableForBookmarkFile, includingResourceValuesForKeys: nil, relativeTo: nil)
                var dst = u.deletingLastPathComponent().appendingPathComponent(u.lastPathComponent + " alias")
                var n = 2
                while FileManager.default.fileExists(atPath: dst.path) {
                    dst = u.deletingLastPathComponent().appendingPathComponent("\(u.lastPathComponent) alias \(n)")
                    n += 1
                }
                try URL.writeBookmarkData(data, to: dst)
            } catch {
                Dialogs.message("Non riesco a creare l'alias di \"\(u.lastPathComponent)\"", info: error.localizedDescription, style: .warning)
            }
        }
    }

    // MARK: - Tag

    private func tagsItem(_ items: [FileItem], panel: FilePanel) -> NSMenuItem {
        let names = ["Nessuno", "Grigio", "Verde", "Viola", "Blu", "Giallo", "Rosso", "Arancione"]
        let order = [6, 7, 5, 2, 4, 3, 1, 0]   // come nel Finder: rosso, arancione, giallo, verde, blu, viola, grigio
        let sub = NSMenu()
        let current = Set(items.map(\.label))
        for n in order {
            let i = ActionMenuItem(names[n]) { [weak panel] in
                for it in items {
                    var u = it.url
                    var v = URLResourceValues()
                    v.labelNumber = n
                    try? u.setResourceValues(v)
                }
                panel?.refresh()
            }
            if let c = Icons.labelColor(n) {
                i.image = NSImage(size: NSSize(width: 12, height: 12), flipped: false) { r in
                    c.setFill()
                    NSBezierPath(ovalIn: r.insetBy(dx: 1, dy: 1)).fill()
                    return true
                }
            }
            i.state = current == [n] ? .on : .off
            sub.addItem(i)
        }
        let item = NSMenuItem(title: "Tag", action: nil, keyEquivalent: "")
        item.submenu = sub
        return item
    }
}
