import AppKit
import CommanderCore
import Security

/// Password FTP nel Portachiavi del Mac (servizio "Mac Commander FTP", account = id della connessione).
enum Keychain {
    private static let service = "Mac Commander FTP"

    static func password(for id: UUID) -> String? {
        let q: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service,
                                kSecAttrAccount as String: id.uuidString, kSecReturnData as String: true]
        var out: AnyObject?
        guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess, let d = out as? Data else { return nil }
        return String(data: d, encoding: .utf8)
    }

    static func set(_ password: String, for id: UUID) {
        delete(id)
        let q: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service,
                                kSecAttrAccount as String: id.uuidString, kSecValueData as String: Data(password.utf8)]
        SecItemAdd(q as CFDictionary, nil)
    }

    static func delete(_ id: UUID) {
        let q: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service,
                                kSecAttrAccount as String: id.uuidString]
        SecItemDelete(q as CFDictionary)
    }
}

// MARK: - Ctrl+F: "Connetti al server FTP"

/// Come in TC: un albero con le cartelle (si aprono e si chiudono, e si ricorda com'erano), le
/// connessioni dentro. Una connessione in una cartella si chiama "Cartella|Nome", come in wcx_ftp.ini.
/// Le connessioni si spostano tra le cartelle trascinandole.
final class FtpConnectDialog: ModalPanel, NSOutlineViewDataSource, NSOutlineViewDelegate {
    enum Result { case connect(FtpConnection), cancel }

    final class Node {
        let path: [String]                 // per le cartelle: i nomi dalla radice
        var connection: FtpConnection?
        var children: [Node] = []
        init(path: [String], connection: FtpConnection? = nil) {
            self.path = path
            self.connection = connection
        }
        var isFolder: Bool { connection == nil }
        var title: String { connection.map { FtpConnectDialog.split($0.name).name } ?? path.last ?? "" }
    }

    private var connections: [FtpConnection]
    private var root = Node(path: [])
    private let outline = NSOutlineView()
    private var result: Result = .cancel

    static let lastKey = "ftp.ultima"
    private static let foldersKey = "ftp.cartelle", openKey = "ftp.cartelleAperte"
    private static let dragType = NSPasteboard.PasteboardType("it.duebytes.maccommander.ftp")

    static func run() -> Result {
        let d = FtpConnectDialog()
        let r = d.runModal { [weak d] e in d?.handleKey(e) ?? false }
        return r == .OK ? d.result : .cancel
    }

    /// "FINITI|LAVORO: Viale" -> (["FINITI"], "LAVORO: Viale")
    static func split(_ name: String) -> (folders: [String], name: String) {
        let parts = name.components(separatedBy: "|")
        return (Array(parts.dropLast()), parts.last ?? name)
    }

    private init() {
        connections = FtpStore.load()
        super.init(width: 680)
        panel.title = "Connetti al server FTP"
        let col = NSTableColumn(identifier: NSUserInterfaceItemIdentifier("nome"))
        col.title = "Connetti a:"
        outline.addTableColumn(col)
        outline.outlineTableColumn = col
        outline.dataSource = self
        outline.delegate = self
        outline.rowHeight = 20
        outline.allowsTypeSelect = true
        outline.target = self
        outline.doubleAction = #selector(doubleClicked)
        outline.columnAutoresizingStyle = .firstColumnOnlyAutoresizingStyle
        outline.autoresizesOutlineColumn = false
        outline.registerForDraggedTypes([Self.dragType])
        outline.setDraggingSourceOperationMask(.move, forLocal: true)
        let scroll = NSScrollView()
        scroll.documentView = outline
        scroll.hasVerticalScroller = true
        scroll.borderType = .bezelBorder
        scroll.heightAnchor.constraint(equalToConstant: 460).isActive = true

        let buttons: [NSButton] = [
            button("Connetti", key: "\r") { [weak self] in self?.connectSelected() },
            button("Nuova connessione…") { [weak self] in self?.newConnection() },
            button("Nuovo URL…") { [weak self] in self?.newURL() },
            button("Duplica elemento") { [weak self] in self?.duplicate() },
            button("Nuova cartella…") { [weak self] in self?.newFolder() },
            button("Modifica…") { [weak self] in self?.edit() },
            button("Elimina") { [weak self] in self?.remove() },
            button("Importa da Total Commander…") { [weak self] in self?.importFromTC() },
            button("Annulla", key: "\u{1b}") { [weak self] in self?.finish(.cancel) },
        ]
        let side = NSStackView(views: buttons)
        side.orientation = .vertical
        side.alignment = .leading
        side.spacing = 6
        side.setCustomSpacing(16, after: buttons[0])
        side.setCustomSpacing(16, after: buttons[4])
        side.setCustomSpacing(16, after: buttons[7])
        for b in buttons { b.widthAnchor.constraint(equalToConstant: 210).isActive = true }
        let row = NSStackView(views: [scroll, side])
        row.alignment = .top
        row.spacing = 12
        panel.contentView = column([row], width: 680)
        rebuild()
        if let last = UserDefaults.standard.string(forKey: Self.lastKey), let c = connections.first(where: { $0.id.uuidString == last }) {
            select(c.id)
        } else if outline.numberOfRows > 0 {
            outline.selectRowIndexes(IndexSet(integer: 0), byExtendingSelection: false)
        }
        panel.initialFirstResponder = outline
    }

    // MARK: Albero

    private var storedFolders: [String] {
        get { UserDefaults.standard.stringArray(forKey: Self.foldersKey) ?? [] }
        set { UserDefaults.standard.set(Array(Set(newValue)).sorted(), forKey: Self.foldersKey) }
    }
    private var openFolders: Set<String> {
        get { Set(UserDefaults.standard.stringArray(forKey: Self.openKey) ?? []) }
        set { UserDefaults.standard.set(Array(newValue).sorted(), forKey: Self.openKey) }
    }

    /// Ricostruisce l'albero: cartelle prima, poi le connessioni, in ordine alfabetico (come TC).
    private func rebuild() {
        let r = Node(path: [])
        var folders: [String: Node] = ["": r]
        func folder(_ path: [String]) -> Node {
            let key = path.joined(separator: "|")
            if let f = folders[key] { return f }
            let parent = folder(Array(path.dropLast()))
            let f = Node(path: path)
            parent.children.append(f)
            folders[key] = f
            return f
        }
        for f in storedFolders where !f.isEmpty { _ = folder(f.components(separatedBy: "|")) }
        for c in connections { folder(Self.split(c.name).folders).children.append(Node(path: [], connection: c)) }
        func sort(_ n: Node) {
            n.children.sort { a, b in
                if a.isFolder != b.isFolder { return a.isFolder }
                return a.title.localizedStandardCompare(b.title) == .orderedAscending
            }
            n.children.filter(\.isFolder).forEach(sort)
        }
        sort(r)
        root = r
        // Le cartelle che esistono si ricordano anche vuote.
        storedFolders = folders.keys.filter { !$0.isEmpty }
        outline.reloadData()
        let open = openFolders
        func expand(_ n: Node) {
            for c in n.children where c.isFolder {
                if open.contains(c.path.joined(separator: "|")) { outline.expandItem(c) }
                expand(c)
            }
        }
        expand(r)
    }

    private func save() { try? FtpStore.save(connections) }

    private var selectedNode: Node? { outline.item(atRow: outline.selectedRow) as? Node }
    private var selected: FtpConnection? { selectedNode?.connection }

    /// La cartella in cui mettere una cosa nuova: quella selezionata, o quella della connessione selezionata.
    private var targetFolder: [String] {
        guard let n = selectedNode else { return [] }
        return n.isFolder ? n.path : Self.split(n.connection!.name).folders
    }

    private func find(_ pred: (Node) -> Bool, in n: Node? = nil) -> Node? {
        for c in (n ?? root).children {
            if pred(c) { return c }
            if c.isFolder, let f = find(pred, in: c) { return f }
        }
        return nil
    }

    private func select(_ id: UUID) {
        guard let node = find({ $0.connection?.id == id }) else { return }
        reveal(node)
    }

    private func selectFolder(_ path: [String]) {
        guard let node = find({ $0.isFolder && $0.path == path }) else { return }
        reveal(node)
    }

    private func reveal(_ node: Node) {
        // Si aprono le cartelle che lo contengono.
        var chain: [Node] = []
        var cur: Node? = node
        while let c = cur, let p = outline.parent(forItem: c) as? Node { chain.insert(p, at: 0); cur = p }
        if chain.isEmpty, let c = node.connection {
            let folders = Self.split(c.name).folders
            for i in folders.indices {
                if let f = find({ $0.isFolder && $0.path == Array(folders[...i]) }) { outline.expandItem(f) }
            }
        }
        chain.forEach { outline.expandItem($0) }
        let row = outline.row(forItem: node)
        if row >= 0 {
            outline.selectRowIndexes(IndexSet(integer: row), byExtendingSelection: false)
            outline.scrollRowToVisible(row)
        }
        panel.makeFirstResponder(outline)
    }

    func outlineView(_ o: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int { ((item as? Node) ?? root).children.count }
    func outlineView(_ o: NSOutlineView, child index: Int, ofItem item: Any?) -> Any { ((item as? Node) ?? root).children[index] }
    func outlineView(_ o: NSOutlineView, isItemExpandable item: Any) -> Bool { (item as? Node)?.isFolder ?? false }

    func outlineView(_ o: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
        guard let n = item as? Node else { return nil }
        let cell = (o.makeView(withIdentifier: NSUserInterfaceItemIdentifier("c"), owner: self) as? NameCell)
            ?? NameCell(identifier: NSUserInterfaceItemIdentifier("c"), withIcon: true)
        cell.label.stringValue = n.title
        cell.label.textColor = .labelColor
        if let c = n.connection {
            cell.icon.image = NSImage(systemSymbolName: c.tls || c.implicitTLS ? "lock.doc" : "globe", accessibilityDescription: nil)
            cell.icon.contentTintColor = nil
            cell.toolTip = "\(c.user.isEmpty ? "" : c.user + "@")\(c.host)\(c.remoteDir)"
        } else {
            cell.icon.image = NSImage(systemSymbolName: "folder.fill", accessibilityDescription: "cartella")
            cell.icon.contentTintColor = .systemYellow
            cell.toolTip = nil
        }
        return cell
    }

    func outlineView(_ o: NSOutlineView, typeSelectStringFor tableColumn: NSTableColumn?, item: Any) -> String? { (item as? Node)?.title }

    func outlineViewItemDidExpand(_ notification: Notification) {
        guard let n = notification.userInfo?["NSObject"] as? Node else { return }
        openFolders.insert(n.path.joined(separator: "|"))
    }

    func outlineViewItemDidCollapse(_ notification: Notification) {
        guard let n = notification.userInfo?["NSObject"] as? Node else { return }
        openFolders.remove(n.path.joined(separator: "|"))
    }

    // MARK: Trascinare nelle cartelle

    func outlineView(_ o: NSOutlineView, pasteboardWriterForItem item: Any) -> NSPasteboardWriting? {
        guard let n = item as? Node else { return nil }
        let pb = NSPasteboardItem()
        pb.setString(n.connection.map { "c:" + $0.id.uuidString } ?? "f:" + n.path.joined(separator: "|"), forType: Self.dragType)
        return pb
    }

    func outlineView(_ o: NSOutlineView, validateDrop info: NSDraggingInfo, proposedItem item: Any?, proposedChildIndex index: Int) -> NSDragOperation {
        let target = item as? Node
        if let t = target, !t.isFolder { return [] }   // si lascia solo sulle cartelle o fuori
        o.setDropItem(target, dropChildIndex: NSOutlineViewDropOnItemIndex)
        return .move
    }

    func outlineView(_ o: NSOutlineView, acceptDrop info: NSDraggingInfo, item: Any?, childIndex index: Int) -> Bool {
        guard let s = info.draggingPasteboard.string(forType: Self.dragType) else { return false }
        let dest = (item as? Node)?.path ?? []
        if s.hasPrefix("c:"), let id = UUID(uuidString: String(s.dropFirst(2))), let i = connections.firstIndex(where: { $0.id == id }) {
            connections[i].name = (dest + [Self.split(connections[i].name).name]).joined(separator: "|")
            save()
            rebuild()
            select(id)
            return true
        }
        if s.hasPrefix("f:") {
            let path = String(s.dropFirst(2)).components(separatedBy: "|")
            guard !dest.starts(with: path) else { return false }   // non dentro se stessa
            moveFolder(path, to: dest + [path.last!])
            return true
        }
        return false
    }

    /// Cambia il percorso di una cartella (rinomina o sposta), con tutto quello che contiene.
    private func moveFolder(_ old: [String], to new: [String]) {
        let o = old.joined(separator: "|"), n = new.joined(separator: "|")
        for i in connections.indices where connections[i].name.hasPrefix(o + "|") {
            connections[i].name = n + connections[i].name.dropFirst(o.count)
        }
        storedFolders = storedFolders.map { $0 == o ? n : ($0.hasPrefix(o + "|") ? n + $0.dropFirst(o.count) : $0) }
        openFolders = Set(openFolders.map { $0 == o ? n : ($0.hasPrefix(o + "|") ? n + $0.dropFirst(o.count) : $0) })
        save()
        rebuild()
        selectFolder(new)
    }

    // MARK: Pulsanti

    @objc private func doubleClicked() {
        guard let n = outline.item(atRow: outline.clickedRow) as? Node else { return }
        if n.isFolder { toggle(n) } else { connectSelected() }
    }

    private func toggle(_ n: Node) {
        if outline.isItemExpanded(n) { outline.collapseItem(n) } else { outline.expandItem(n) }
    }

    @objc private func connectSelected() {
        if let n = selectedNode, n.isFolder { toggle(n); return }
        guard let c = selected else { NSSound.beep(); return }
        UserDefaults.standard.set(c.id.uuidString, forKey: Self.lastKey)
        result = .connect(c)
        finish(.OK)
    }

    private func newConnection() {
        let folder = targetFolder
        guard var (c, pwd) = FtpEditDialog.run(FtpConnection(name: "", host: ""), password: nil) else { panel.makeKeyAndOrderFront(nil); return }
        c.name = (folder + [c.name]).joined(separator: "|")
        connections.append(c)
        if let pwd { Keychain.set(pwd, for: c.id) }
        save()
        rebuild()
        select(c.id)
    }

    private func newURL() {
        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://") else { return }
        guard let c = FtpConnectDialog.connection(fromURL: text) else { NSSound.beep(); return }
        result = .connect(c)
        finish(.OK)
    }

    static func connection(fromURL text: String) -> FtpConnection? {
        var t = text.trimmingCharacters(in: .whitespaces)
        guard !t.isEmpty, t != "ftp://" else { return nil }
        if !t.contains("://") { t = "ftp://" + t }
        guard let u = URLComponents(string: t), let host = u.host else { return nil }
        var c = FtpConnection(name: host, host: host + (u.port.map { ":\($0)" } ?? ""))
        c.user = u.user ?? ""
        c.tls = u.scheme == "ftpes" || u.scheme == "ftps"
        c.implicitTLS = u.scheme == "ftpis"
        c.remoteDir = u.path
        return c
    }

    private func duplicate() {
        guard var c = selected else { NSSound.beep(); return }
        let old = c.id
        c.id = UUID()
        c.name += " (copia)"
        connections.append(c)
        if let p = Keychain.password(for: old) { Keychain.set(p, for: c.id) }
        save()
        rebuild()
        select(c.id)
    }

    private func newFolder() {
        let parent = targetFolder
        guard case .ok(let raw) = Dialogs.prompt("Nuova cartella:", info: parent.isEmpty ? "" : "Dentro \"\(parent.joined(separator: " › "))\"",
                                                 value: "") else { return }
        let name = raw.replacingOccurrences(of: "|", with: "-").trimmingCharacters(in: .whitespaces)
        guard !name.isEmpty else { return }
        let path = parent + [name]
        storedFolders = storedFolders + [path.joined(separator: "|")]
        rebuild()
        selectFolder(path)
    }

    private func edit() {
        guard let n = selectedNode else { return }
        if n.isFolder {
            guard case .ok(let raw) = Dialogs.prompt("Nome della cartella:", value: n.title) else { return }
            let name = raw.replacingOccurrences(of: "|", with: "-").trimmingCharacters(in: .whitespaces)
            guard !name.isEmpty, name != n.title else { return }
            moveFolder(n.path, to: Array(n.path.dropLast()) + [name])
            return
        }
        guard let c = n.connection, let i = connections.firstIndex(where: { $0.id == c.id }) else { return }
        // Nella finestra si vede solo il nome; la cartella resta quella.
        let (folders, shortName) = Self.split(c.name)
        var shown = c
        shown.name = shortName
        guard var (edited, pwd) = FtpEditDialog.run(shown, password: Keychain.password(for: c.id)) else { return }
        edited.name = (folders + [edited.name.replacingOccurrences(of: "|", with: "-")]).joined(separator: "|")
        connections[i] = edited
        if let pwd { Keychain.set(pwd, for: edited.id) } else { Keychain.delete(edited.id) }
        save()
        rebuild()
        select(edited.id)
    }

    private func remove() {
        guard let n = selectedNode else { return }
        if n.isFolder {
            let key = n.path.joined(separator: "|")
            let inside = connections.filter { $0.name.hasPrefix(key + "|") }
            let info = inside.isEmpty ? "" : "Le \(inside.count) connessioni che contiene restano, fuori dalla cartella."
            guard Dialogs.confirm("Eliminare la cartella \"\(n.title)\"?", info: info, ok: "Elimina") else { return }
            // Il contenuto sale di un livello.
            let parent = Array(n.path.dropLast()).joined(separator: "|")
            for i in connections.indices where connections[i].name.hasPrefix(key + "|") {
                let rest = connections[i].name.dropFirst(key.count + 1)
                connections[i].name = parent.isEmpty ? String(rest) : parent + "|" + rest
            }
            storedFolders = storedFolders.compactMap { f in
                if f == key { return nil }
                if f.hasPrefix(key + "|") { let rest = f.dropFirst(key.count + 1); return parent.isEmpty ? String(rest) : parent + "|" + rest }
                return f
            }
            save()
            rebuild()
            return
        }
        guard let c = n.connection else { return }
        guard Dialogs.confirm("Eliminare la connessione \"\(n.title)\"?", ok: "Elimina") else { return }
        connections.removeAll { $0.id == c.id }
        Keychain.delete(c.id)
        save()
        rebuild()
    }

    /// Le connessioni e le password di Total Commander (wcx_ftp.ini, nella cartella GHISLER di Windows).
    private func importFromTC() {
        let op = NSOpenPanel()
        op.message = "Scegli il file wcx_ftp.ini di Total Commander"
        op.canChooseDirectories = false
        guard op.runModal() == .OK, let url = op.url else { panel.makeKeyAndOrderFront(nil); return }
        panel.makeKeyAndOrderFront(nil)
        if let summary = TCImporter.merge(from: url) {
            connections = FtpStore.load()
            rebuild()
            Dialogs.message("Importazione fatta", info: summary)
        }
    }

    private func handleKey(_ e: NSEvent) -> Bool {
        guard NSApp.keyWindow === panel else { return false }
        let mods = e.modifierFlags.intersection([.control, .option, .command, .shift])
        guard mods.isEmpty else { return false }
        switch e.keyCode {
        case KeyCode.returnKey, KeyCode.keypadEnter:
            if let b = panel.firstResponder as? ActionButton, b.tabStop { return false }   // Invio sul pulsante scelto con Tab
            connectSelected()
            return true
        case KeyCode.f4: edit(); return true
        case KeyCode.f7: newFolder(); return true
        case KeyCode.forwardDelete: remove(); return true
        default: return false
        }
    }
}

/// Unisce un wcx_ftp.ini di TC alle connessioni: quelle con lo stesso nome ricevono la password
/// (se non ce l'hanno già), le altre si aggiungono.
enum TCImporter {
    /// Il riassunto da mostrare, o nil se il file non si legge.
    static func merge(from url: URL) -> String? {
        guard let data = try? Data(contentsOf: url) else {
            Dialogs.message("Non riesco a leggere \(url.lastPathComponent)", style: .warning)
            return nil
        }
        let text = String(data: data, encoding: .utf8) ?? String(data: data, encoding: .windowsCP1252) ?? ""
        let imported = TCFtpImport.parse(text, withPasswords: true)
        var list = FtpStore.load()
        var added = 0, passwords = 0
        var moved = 0
        for i in imported {
            // Stesso nome; oppure stesso nome senza cartella, se in TC è stata spostata in una cartella.
            let short = FtpConnectDialog.split(i.connection.name).name
            var idx = list.firstIndex(where: { $0.name == i.connection.name })
            if idx == nil {
                let same = list.indices.filter { FtpConnectDialog.split(list[$0].name).name == short }
                if same.count == 1 {
                    idx = same[0]
                    list[same[0]].name = i.connection.name
                    moved += 1
                }
            }
            if let idx {
                let existing = list[idx]
                if Keychain.password(for: existing.id) == nil, let p = i.password {
                    Keychain.set(p, for: existing.id)
                    passwords += 1
                }
            } else {
                list.append(i.connection)
                if let p = i.password { Keychain.set(p, for: i.connection.id); passwords += 1 }
                added += 1
            }
        }
        try? FtpStore.save(list)
        let noPwd = imported.filter { $0.password == nil }.count
        var s = "\(passwords) password messe nel Portachiavi, \(added) connessioni nuove."
        if moved > 0 { s += " \(moved) spostate nella cartella che hanno in TC." }
        if noPwd > 0 { s += " \(noPwd) password non si possono leggere (protette dalla password principale di TC): te le chiedo quando ti colleghi." }
        return s
    }
}

// MARK: - Dettagli della connessione

final class FtpEditDialog: ModalPanel {
    private let session = NSTextField()
    private let host = NSTextField()
    private let tls = NSButton(checkboxWithTitle: "SSL/TLS", target: nil, action: nil)
    private let user = NSTextField()
    private let password = NSSecureTextField()
    private let remote = NSTextField()
    private let local = NSTextField()
    private let passive = NSButton(checkboxWithTitle: "Usa la modalità passiva (come un browser)", target: nil, action: nil)
    private var conn: FtpConnection

    static func run(_ c: FtpConnection, password: String?) -> (FtpConnection, String?)? {
        let d = FtpEditDialog(c, password: password)
        guard d.runModal(handler: { _ in false }) == .OK else { return nil }
        return d.read()
    }

    private init(_ c: FtpConnection, password pwd: String?) {
        conn = c
        super.init(width: 560)
        panel.title = c.name.isEmpty ? "Nuova connessione" : "Dettagli della connessione"
        session.stringValue = c.name
        host.stringValue = c.host
        tls.state = c.tls || c.implicitTLS ? .on : .off
        user.stringValue = c.user
        password.stringValue = pwd ?? ""
        remote.stringValue = c.remoteDir
        local.stringValue = c.localDir
        passive.state = c.passive ? .on : .off
        session.placeholderString = "Nome che vedi nell'elenco"
        host.placeholderString = "ftp.sito.it oppure ftp.sito.it:2121"
        password.placeholderString = "Vuota = la chiedo quando ti colleghi"
        remote.placeholderString = "/public_html"
        local.placeholderString = "Cartella che si apre nell'altro pannello"
        let browse = button("…") { [weak self] in self?.chooseLocal() }
        let localRow = NSStackView(views: [local, browse])
        let hostRow = NSStackView(views: [host, tls])
        let grid = NSGridView(views: [
            [NSTextField(labelWithString: "Sessione:"), session],
            [NSTextField(labelWithString: "Server[:porta]:"), hostRow],
            [NSTextField(labelWithString: "Utente:"), user],
            [NSTextField(labelWithString: "Password:"), password],
            [NSTextField(labelWithString: "Cartella remota:"), remote],
            [NSTextField(labelWithString: "Cartella locale:"), localRow],
            [NSGridCell.emptyContentView, passive],
        ])
        grid.rowSpacing = 8
        grid.column(at: 0).xPlacement = .trailing
        grid.column(at: 1).width = 400
        let ok = button("OK", key: "\r") { [weak self] in self?.confirm() }
        let cancel = button("Annulla", key: "\u{1b}") { [weak self] in self?.finish(.cancel) }
        let buttons = NSStackView(views: [NSView(), cancel, ok])
        panel.contentView = column([grid, buttons], width: 560)
        panel.initialFirstResponder = session.stringValue.isEmpty ? session : host
    }

    private func chooseLocal() {
        let op = NSOpenPanel()
        op.canChooseFiles = false
        op.canChooseDirectories = true
        if op.runModal() == .OK, let u = op.url { local.stringValue = HotlistStore.storedPath(u) }
        panel.makeKeyAndOrderFront(nil)
    }

    private func confirm() {
        guard !host.stringValue.trimmingCharacters(in: .whitespaces).isEmpty else { NSSound.beep(); return }
        finish(.OK)
    }

    private func read() -> (FtpConnection, String?) {
        var c = conn
        var h = host.stringValue.trimmingCharacters(in: .whitespaces)
        c.implicitTLS = h.lowercased().hasPrefix("ftpis://")
        for prefix in ["ftp://", "ftps://", "ftpes://", "ftpis://"] where h.lowercased().hasPrefix(prefix) { h = String(h.dropFirst(prefix.count)) }
        c.host = h
        c.name = session.stringValue.isEmpty ? h : session.stringValue
        c.tls = tls.state == .on && !c.implicitTLS
        c.user = user.stringValue
        c.remoteDir = remote.stringValue
        c.localDir = local.stringValue
        c.passive = passive.state == .on
        let p = password.stringValue
        return (c, p.isEmpty ? nil : p)
    }
}
