import AppKit
import CommanderCore

/// FTP nel pannello: Ctrl+F, Ctrl+Shift+F, Ctrl+N, e F3/F4/F5/F6/F7/F8 quando un pannello è su un server.
extension MainWindowController {
    // MARK: - Collegarsi

    func ftpConnect() {
        importTCConnectionsIfNeeded()
        guard case .connect(let c) = FtpConnectDialog.run() else { return }
        connect(c, saved: true)
    }

    func ftpNewURL() {
        guard case .ok(let text) = Dialogs.prompt("Server o indirizzo FTP:", info: "Per esempio ftp.sito.it oppure ftp://utente@ftp.sito.it/cartella",
                                                  value: "ftp://"),
              let c = FtpConnectDialog.connection(fromURL: text) else { return }
        connect(c, saved: false)
    }

    func connect(_ c: FtpConnection, saved: Bool, password known: String? = nil) {
        var pwd = known ?? (saved ? Keychain.password(for: c.id) : nil)
        if pwd == nil && !c.user.isEmpty && c.user != "anonymous" {
            guard let p = askPassword(for: c) else { return }
            pwd = p
            if saved { Keychain.set(p, for: c.id) }
        }
        let session = FtpSession(connection: c, password: pwd ?? "")
        attempt(session, saved: saved)
    }

    private func askPassword(for c: FtpConnection) -> String? {
        let a = NSAlert()
        a.messageText = "Password per \(c.user)@\(c.host)"
        let f = NSSecureTextField(frame: NSRect(x: 0, y: 0, width: 300, height: 24))
        a.accessoryView = f
        a.addButton(withTitle: "Collegati")
        a.addButton(withTitle: "Annulla").keyEquivalent = "\u{1b}"
        a.window.initialFirstResponder = f
        guard a.runCentered() == .alertFirstButtonReturn else { return nil }
        return f.stringValue
    }

    private func attempt(_ session: FtpSession, saved: Bool) {
        let panel = active
        let c = session.connection
        panel.showMessage("Collegamento a \(c.host)…")
        DispatchQueue.global(qos: .userInitiated).async {
            let result = Result { () -> String in
                let dir = c.remoteDir.isEmpty ? try session.homeDirectory() : c.remoteDir
                _ = try session.list(dir)
                return dir
            }
            DispatchQueue.main.async { [weak self] in
                guard let self else { return }
                switch result {
                case .success(let dir):
                    let id = FtpRegistry.register(session)
                    panel.navigate(to: FtpRegistry.url(id: id, path: dir))
                    let local = (c.localDir as NSString).expandingTildeInPath
                    if !c.localDir.isEmpty, FileManager.default.fileExists(atPath: local) {
                        (panel === self.left ? self.right : self.left).navigate(to: URL(fileURLWithPath: local, isDirectory: true))
                    }
                case .failure(let e as FtpError) where e.isCertificateProblem && !session.allowInvalidCertificate:
                    panel.updateStatus()
                    if Dialogs.confirm("Il certificato di \(c.host) non è valido",
                                       info: "Succede spesso con gli hosting condivisi. Collegarsi comunque, con la connessione cifrata?",
                                       ok: "Collegati") {
                        session.allowInvalidCertificate = true
                        self.attempt(session, saved: saved)
                    }
                case .failure(let e as FtpError) where e.isLoginProblem:
                    panel.updateStatus()
                    Dialogs.message("Accesso rifiutato da \(c.host)", info: "Utente o password sbagliati.", style: .warning)
                    if let p = self.askPassword(for: c) {
                        if saved { Keychain.set(p, for: c.id) }
                        self.connect(c, saved: saved, password: p)
                    }
                case .failure(let e):
                    panel.updateStatus()
                    Dialogs.message("Non riesco a collegarmi a \(c.host)", info: e.localizedDescription, style: .warning)
                }
            }
        }
    }

    /// Ctrl+Shift+F: torna all'ultima cartella del Mac e chiude la connessione se nessuno la usa più.
    func ftpDisconnect() {
        let p = active
        guard p.isRemote, let id = p.currentURL.host else { NSSound.beep(); return }
        let back = p.tab.history.last(where: \.isFileURL) ?? FileManager.default.homeDirectoryForCurrentUser
        p.navigate(to: back)
        let stillUsed = [left, right].flatMap(\.tabs).contains { $0.url.host == id && FtpRegistry.isRemote($0.url) }
        if !stillUsed { FtpRegistry.remove(id) }
    }

    /// Un wcx_ftp.ini di TC messo in "Application Support/Mac Commander/import": connessioni e password
    /// si uniscono a quelle che ci sono, poi il file si cancella (contiene le password).
    func importTCConnectionsIfNeeded() {
        let file = FtpStore.defaultURL.deletingLastPathComponent().appendingPathComponent("import/wcx_ftp.ini")
        guard FileManager.default.fileExists(atPath: file.path) else { return }
        let summary = TCImporter.merge(from: file)
        try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
        if let summary { Dialogs.message("Connessioni di Total Commander importate", info: summary) }
    }

    // MARK: - File sul server

    private static var tempRoot: URL {
        FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("MacCommander-ftp")
    }

    /// Scarica un file in una cartella temporanea (per F3, F4, Invio).
    func downloadTemp(_ item: FileItem, then: @escaping (URL) -> Void) {
        guard let s = FtpRegistry.session(for: item.url) else { return }
        let dir = Self.tempRoot.appendingPathComponent(UUID().uuidString)
        try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
        let local = dir.appendingPathComponent(item.name)
        let panel = active
        panel.showMessage("Scarico \(item.name)…")
        DispatchQueue.global(qos: .userInitiated).async {
            let r = Result { try s.download(item.url.path, to: local) { _ in true } }
            DispatchQueue.main.async {
                panel.updateStatus()
                switch r {
                case .success:
                    Quarantine.mark(local)
                    then(local)
                case .failure(let e): Dialogs.message("Non riesco a scaricare \(item.name)", info: e.localizedDescription, style: .warning)
                }
            }
        }
    }

    func remoteOpen(_ item: FileItem) {
        downloadTemp(item) { NSWorkspace.shared.open($0) }
    }

    func remoteView(_ item: FileItem) {
        downloadTemp(item) { ViewerWindowController.show($0) }
    }

    /// F4 su un file del server: si apre in TextEdit e, quando lo salvi, chiede se ricaricarlo.
    func remoteEdit(_ item: FileItem) {
        let panel = active
        downloadTemp(item) { local in
            RemoteEditWatcher.watch(local: local, remote: item.url) { panel.refresh() }
            NSWorkspace.shared.open([local], withApplicationAt: URL(fileURLWithPath: "/System/Applications/TextEdit.app"),
                                    configuration: NSWorkspace.OpenConfiguration())
        }
    }

    func remoteMakeDirectory(name: String) {
        let p = active
        guard let s = FtpRegistry.session(for: p.currentURL) else { return }
        let path = p.currentURL.appendingPathComponent(name).path
        DispatchQueue.global(qos: .userInitiated).async {
            let r = Result { try s.makeDirectory(path) }
            DispatchQueue.main.async {
                if case .failure(let e) = r { Dialogs.message("Non riesco a creare la cartella", info: e.localizedDescription, style: .warning) }
                p.tab.cursorName = name
                p.refresh()
            }
        }
    }

    func remoteDelete(_ items: [FileItem]) {
        let p = active
        guard let s = FtpRegistry.session(for: p.currentURL) else { return }
        let what = items.count == 1 ? "\"\(items[0].name)\"" : "\(items.count) elementi"
        guard Dialogs.confirm("Eliminare \(what) dal server?", info: "Sul server non c'è il Cestino: si cancellano definitivamente.", ok: "Elimina") else { return }
        p.showMessage("Elimino \(what)…")
        DispatchQueue.global(qos: .userInitiated).async {
            var errors: [String] = []
            for i in items {
                do { try s.deleteRecursively(i.url.path, isDirectory: i.showsAsFolder) } catch { errors.append("\(i.name): \(error.localizedDescription)") }
            }
            DispatchQueue.main.async {
                if !errors.isEmpty { Dialogs.message("Alcuni elementi non sono stati eliminati", info: errors.prefix(5).joined(separator: "\n"), style: .warning) }
                p.clearMarksAfterOperation()
                p.refresh()
            }
        }
    }

    /// F5/F6 quando uno dei due pannelli è su un server.
    func remoteCopyOrMove(_ kind: TransferKind, items: [FileItem], from source: FilePanel, to target: FilePanel) {
        if source.isRemote && target.isRemote {
            Dialogs.message("Copia tra due server", info: "Per ora si copia solo tra il Mac e un server: scarica prima i file sul Mac.")
            return
        }
        let initial = Format.path(target.currentURL) + (target.currentURL.path == "/" ? "*.*" : "/*.*")
        guard let opts = CopyDialog.run(kind: kind, items: items, target: initial) else { return }
        var destDir: URL
        var name: String?
        var pattern: String?
        if target.isRemote, let id = target.currentURL.host {
            // "Sito:/cartella/*.*" -> "/cartella", "*.*"
            var text = opts.target
            if let s = FtpRegistry.session(for: target.currentURL), text.hasPrefix(s.connection.name + ":") {
                text = String(text.dropFirst(s.connection.name.count + 1))
            }
            if !text.hasPrefix("/") { text = target.currentURL.path + "/" + text }
            let last = (text as NSString).lastPathComponent
            let dirPath = text.hasSuffix("/") ? text : (text as NSString).deletingLastPathComponent
            if text.hasSuffix("/") {
                destDir = FtpRegistry.url(id: id, path: dirPath)
            } else if last.contains("*") || last.contains("?") {
                destDir = FtpRegistry.url(id: id, path: dirPath)
                pattern = last == "*.*" || last == "*" ? nil : last
            } else if items.count == 1 {
                destDir = FtpRegistry.url(id: id, path: dirPath)
                name = last
            } else {
                destDir = FtpRegistry.url(id: id, path: text)
            }
        } else {
            var text = (opts.target.trimmingCharacters(in: .whitespaces) as NSString).expandingTildeInPath
            let last = (text as NSString).lastPathComponent
            if last.contains("*") || last.contains("?") {
                pattern = last == "*.*" || last == "*" ? nil : last
                text = (text as NSString).deletingLastPathComponent
            } else if items.count == 1 && !text.hasSuffix("/") && !FileManager.default.fileExists(atPath: text) {
                name = last
                text = (text as NSString).deletingLastPathComponent
            }
            destDir = URL(fileURLWithPath: text, isDirectory: true)
        }
        var job = TransferJob(kind: kind, sources: items.map(\.url), destination: destDir, newName: name,
                              renamePattern: pattern, policy: opts.policy)
        if source.isRemote {
            job.directorySources = Set(items.filter(\.showsAsFolder).map(\.url))
            job.sizes = Dictionary(uniqueKeysWithValues: items.map { ($0.url, $0.size) })
        }
        queue.enqueue(job)
        source.clearMarksAfterOperation()
    }

    /// Ctrl+V in un pannello FTP: carica i file copiati dal Finder o da un altro pannello.
    func remotePaste(_ urls: [URL]) {
        guard active.isRemote else { return }
        queue.enqueue(TransferJob(kind: .copy, sources: urls, destination: active.currentURL))
    }
}

/// Dopo F4 su un file del server: quando il file viene salvato, chiede se ricaricarlo.
final class RemoteEditWatcher {
    private static var active: [URL: RemoteEditWatcher] = [:]

    private let local: URL
    private let remote: URL
    private let onUpload: () -> Void
    private var source: DispatchSourceFileSystemObject?
    private var lastDate: Date?
    private var asking = false

    static func watch(local: URL, remote: URL, onUpload: @escaping () -> Void) {
        active[local] = RemoteEditWatcher(local: local, remote: remote, onUpload: onUpload)
    }

    private init(local: URL, remote: URL, onUpload: @escaping () -> Void) {
        self.local = local
        self.remote = remote
        self.onUpload = onUpload
        lastDate = modified()
        // Si osserva la cartella: TextEdit salva scrivendo un file nuovo al posto del vecchio.
        let fd = open(local.deletingLastPathComponent().path, O_EVTONLY)
        guard fd >= 0 else { return }
        let s = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fd, eventMask: [.write, .rename, .link], queue: .main)
        s.setEventHandler { [weak self] in
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { self?.changed() }
        }
        s.setCancelHandler { close(fd) }
        s.resume()
        source = s
    }

    private func modified() -> Date? {
        try? local.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate
    }

    private func changed() {
        guard !asking, let d = modified(), d != lastDate else { return }
        lastDate = d
        asking = true
        defer { asking = false }
        guard let s = FtpRegistry.session(for: remote) else { return }
        Dialogs.bringForward()
        guard Dialogs.confirm("Hai modificato \"\(local.lastPathComponent)\"", info: "Lo ricarico sul server (\(Format.path(remote)))?", ok: "Carica") else { return }
        let local = self.local, remote = self.remote, done = onUpload
        DispatchQueue.global(qos: .userInitiated).async {
            let r = Result { try s.upload(local, to: remote.path) { _ in true } }
            DispatchQueue.main.async {
                if case .failure(let e) = r { Dialogs.message("Non riesco a caricare il file", info: e.localizedDescription, style: .warning) }
                done()
            }
        }
    }
}
