import XCTest
@testable import CommanderCore

final class MatcherTests: XCTestCase {
    func testMasks() {
        XCTAssertTrue(Matcher.matches("foto.JPG", mask: "*.jpg"))
        XCTAssertTrue(Matcher.matches("LEGGIMI", mask: "*.*"))
        XCTAssertTrue(Matcher.matches("a.png", mask: "*.jpg;*.png"))
        XCTAssertTrue(Matcher.matches("a.png", mask: "*.jpg *.png"))
        XCTAssertFalse(Matcher.matches("a.gif", mask: "*.jpg *.png"))
    }

    func testQuickFilter() {
        XCTAssertTrue(Matcher.quickFilter("Siti Web", filter: "sit"))
        XCTAssertTrue(Matcher.quickFilter("Città", filter: "citta"))
        XCTAssertFalse(Matcher.quickFilter("Siti Web", filter: "web"))
        XCTAssertTrue(Matcher.quickFilter("Siti Web", filter: "*web"))
    }

    func testExtension() {
        let f = FileItem(url: URL(fileURLWithPath: "/x/a.tar.gz"), name: "a.tar.gz", isDirectory: false)
        XCTAssertEqual(f.ext, "gz")
        XCTAssertEqual(f.baseName, "a.tar")
        let h = FileItem(url: URL(fileURLWithPath: "/x/.bashrc"), name: ".bashrc", isDirectory: false)
        XCTAssertEqual(h.ext, "")
        let d = FileItem(url: URL(fileURLWithPath: "/x/v1.2"), name: "v1.2", isDirectory: true)
        XCTAssertEqual(d.ext, "")
    }

    func testNamePattern() {
        XCTAssertEqual(NamePattern.apply("*.*", to: "a.txt"), "a.txt")
        XCTAssertEqual(NamePattern.apply("*.bak", to: "a.txt"), "a.bak")
        XCTAssertEqual(NamePattern.apply("copia di *.*", to: "a.txt"), "copia di a.txt")
        XCTAssertEqual(NamePattern.apply("nuovo.txt", to: "a.txt"), "nuovo.txt")
    }

    func testHotlistAccessKey() {
        let e = HotlistEntry(name: "Down&loads", path: "~/Downloads")
        XCTAssertEqual(e.title, "Downloads")
        XCTAssertEqual(e.accessKey, "l")
        XCTAssertEqual(e.url?.path, NSHomeDirectory() + "/Downloads")
    }

    func testMnemonic() {
        let m = Mnemonic("Cd &Images")
        XCTAssertEqual(m.title, "Cd Images")
        XCTAssertEqual(m.key, "i")
        XCTAssertEqual(m.offset, 3)
        XCTAssertEqual(Mnemonic("A && B").title, "A & B")
        XCTAssertNil(Mnemonic("A && B").key)
        XCTAssertEqual(Mnemonic("Installazioni").effectiveKey, "i")

        // Sottomenu "Cd Images": la I senza & porta a Installazioni.
        let sub: [Mnemonic?] = [Mnemonic("Softwares and Drivers"), nil, Mnemonic("Installazioni"), Mnemonic("MAC")]
        XCTAssertEqual(Mnemonic.match("i", in: sub, current: nil), .activate(2))
        XCTAssertEqual(Mnemonic.match("I", in: sub, current: nil), .activate(2))
        XCTAssertEqual(Mnemonic.match("q", in: sub, current: nil), .none)

        // La & vince sulla prima lettera: "x" -> Dropbo&x anche se un'altra voce inizia con X.
        let top: [Mnemonic?] = [Mnemonic("Xcode"), Mnemonic("Dropbo&x")]
        XCTAssertEqual(Mnemonic.match("x", in: top, current: nil), .activate(1))

        // Più voci con la stessa iniziale: si scorre.
        let dup: [Mnemonic?] = [Mnemonic("Mac"), Mnemonic("Musica"), Mnemonic("Foto")]
        XCTAssertEqual(Mnemonic.match("m", in: dup, current: nil), .highlight(0))
        XCTAssertEqual(Mnemonic.match("m", in: dup, current: 0), .highlight(1))
        XCTAssertEqual(Mnemonic.match("m", in: dup, current: 1), .highlight(0))
    }
}

final class TransferTests: XCTestCase, TransferEngineDelegate {
    var root: URL!
    var conflictAnswer: ConflictChoice = .skip
    var conflicts = 0
    var errors: [String] = []

    override func setUpWithError() throws {
        root = FileManager.default.temporaryDirectory.appendingPathComponent("mc-test-\(UUID().uuidString)")
        try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
    }

    override func tearDownWithError() throws {
        try? FileManager.default.removeItem(at: root)
    }

    func engine(_ engine: TransferControl, progress: TransferProgress) {}
    func engine(_ engine: TransferControl, conflictAt destination: URL, source: URL) -> ConflictChoice {
        conflicts += 1
        return conflictAnswer
    }
    func engine(_ engine: TransferControl, error: Error, at url: URL) -> ErrorChoice {
        errors.append(error.localizedDescription)
        return .skip
    }
    func engine(_ engine: TransferControl, trashFailedFor url: URL, error: Error) -> TrashFallback { .skip }

    private func write(_ rel: String, _ text: String) throws {
        let u = root.appendingPathComponent(rel)
        try FileManager.default.createDirectory(at: u.deletingLastPathComponent(), withIntermediateDirectories: true)
        try text.write(to: u, atomically: true, encoding: .utf8)
    }

    private func read(_ rel: String) -> String? {
        try? String(contentsOf: root.appendingPathComponent(rel), encoding: .utf8)
    }

    private func run(_ job: TransferJob) {
        let e = TransferEngine()
        e.delegate = self
        e.run(job)
    }

    func testCopyFolderRecursively() throws {
        try write("src/a.txt", "A")
        try write("src/sub/b.txt", "B")
        run(TransferJob(kind: .copy, sources: [root.appendingPathComponent("src")], destination: root.appendingPathComponent("dst")))
        XCTAssertEqual(read("dst/src/a.txt"), "A")
        XCTAssertEqual(read("dst/src/sub/b.txt"), "B")
        XCTAssertEqual(read("src/a.txt"), "A")
        XCTAssertTrue(errors.isEmpty, "\(errors)")
    }

    /// Date di creazione e modifica uguali all'originale, anche per le cartelle.
    /// Con MC_DATE_TEST_DIR=<cartella sul NAS> la prova si fa anche sul disco di rete.
    func testCopyKeepsDates() throws {
        try write("src/foto/IMG_0001.jpg", "x")
        let created = Date(timeIntervalSince1970: 1_431_246_030)   // 10/05/2015
        let modified = Date(timeIntervalSince1970: 1_465_637_000)  // 11/06/2016
        for rel in ["src/foto/IMG_0001.jpg", "src/foto"] {
            var u = root.appendingPathComponent(rel)
            var v = URLResourceValues()
            v.creationDate = created
            v.contentModificationDate = modified
            try u.setResourceValues(v)
        }
        var targets = [root.appendingPathComponent("dst")]
        if let nas = ProcessInfo.processInfo.environment["MC_DATE_TEST_DIR"] {
            targets.append(URL(fileURLWithPath: nas).appendingPathComponent("mc-test-\(UUID().uuidString)"))
        }
        for dst in targets {
            try FileManager.default.createDirectory(at: dst, withIntermediateDirectories: true)
            defer { if dst != targets[0] { try? FileManager.default.removeItem(at: dst) } }
            run(TransferJob(kind: .copy, sources: [root.appendingPathComponent("src/foto")], destination: dst))
            for rel in ["foto/IMG_0001.jpg", "foto"] {
                let v = try dst.appendingPathComponent(rel).resourceValues(forKeys: [.creationDateKey, .contentModificationDateKey])
                XCTAssertEqual(v.creationDate, created, "\(dst.path) \(rel)")
                XCTAssertEqual(v.contentModificationDate, modified, "\(dst.path) \(rel)")
            }
        }
        XCTAssertTrue(errors.isEmpty, "\(errors)")
    }

    func testConflictSkipKeepsExisting() throws {
        try write("src/a.txt", "nuovo")
        try write("dst/a.txt", "vecchio")
        conflictAnswer = .skip
        run(TransferJob(kind: .copy, sources: [root.appendingPathComponent("src/a.txt")], destination: root.appendingPathComponent("dst")))
        XCTAssertEqual(conflicts, 1)
        XCTAssertEqual(read("dst/a.txt"), "vecchio")
    }

    func testConflictOverwrite() throws {
        try write("src/a.txt", "nuovo")
        try write("dst/a.txt", "vecchio")
        conflictAnswer = .overwrite
        run(TransferJob(kind: .copy, sources: [root.appendingPathComponent("src/a.txt")], destination: root.appendingPathComponent("dst")))
        XCTAssertEqual(read("dst/a.txt"), "nuovo")
    }

    func testMoveMergesFolders() throws {
        try write("src/d/a.txt", "A")
        try write("dst/d/b.txt", "B")
        run(TransferJob(kind: .move, sources: [root.appendingPathComponent("src/d")], destination: root.appendingPathComponent("dst")))
        XCTAssertEqual(read("dst/d/a.txt"), "A")
        XCTAssertEqual(read("dst/d/b.txt"), "B")
        XCTAssertFalse(FileManager.default.fileExists(atPath: root.appendingPathComponent("src/d").path))
    }

    func testCopyWithNewName() throws {
        try write("a.txt", "A")
        run(TransferJob(kind: .copy, sources: [root.appendingPathComponent("a.txt")], destination: root, newName: "b.txt"))
        XCTAssertEqual(read("b.txt"), "A")
        XCTAssertEqual(read("a.txt"), "A")
    }

    func testCopyIntoItselfIsRefused() throws {
        try write("src/a.txt", "A")
        run(TransferJob(kind: .copy, sources: [root.appendingPathComponent("src")], destination: root.appendingPathComponent("src/inner")))
        XCTAssertEqual(errors.count, 1)
    }

    func testFileMaskCopiesOnlyMatching() throws {
        try write("src/a.jpg", "A")
        try write("src/b.txt", "B")
        try write("src/sub/c.jpg", "C")
        try write("src/vuota/d.txt", "D")
        run(TransferJob(kind: .copy, sources: [root.appendingPathComponent("src")], destination: root.appendingPathComponent("dst"), fileMask: "*.jpg"))
        XCTAssertEqual(read("dst/src/a.jpg"), "A")
        XCTAssertEqual(read("dst/src/sub/c.jpg"), "C")
        XCTAssertNil(read("dst/src/b.txt"))
        XCTAssertFalse(FileManager.default.fileExists(atPath: root.appendingPathComponent("dst/src/vuota").path))
    }

    func testAutoRenamePolicy() throws {
        try write("src/a.txt", "nuovo")
        try write("dst/a.txt", "vecchio")
        run(TransferJob(kind: .copy, sources: [root.appendingPathComponent("src/a.txt")], destination: root.appendingPathComponent("dst"), policy: .autoRename))
        XCTAssertEqual(read("dst/a.txt"), "vecchio")
        XCTAssertEqual(read("dst/a (2).txt"), "nuovo")
        XCTAssertEqual(conflicts, 0)
    }

    func testRenameAndAppendChoices() throws {
        try write("src/a.txt", "nuovo")
        try write("dst/a.txt", "vecchio")
        conflictAnswer = .rename("b.txt")
        run(TransferJob(kind: .copy, sources: [root.appendingPathComponent("src/a.txt")], destination: root.appendingPathComponent("dst")))
        XCTAssertEqual(read("dst/b.txt"), "nuovo")
        conflictAnswer = .append
        run(TransferJob(kind: .copy, sources: [root.appendingPathComponent("src/a.txt")], destination: root.appendingPathComponent("dst")))
        XCTAssertEqual(read("dst/a.txt"), "vecchionuovo")
    }

    func testOverwriteOlderPolicy() throws {
        try write("src/a.txt", "nuovo")
        try write("dst/a.txt", "vecchio")
        let old = Date(timeIntervalSinceNow: -3600)
        try FileManager.default.setAttributes([.modificationDate: old], ofItemAtPath: root.appendingPathComponent("dst/a.txt").path)
        try write("src/b.txt", "nuovo")
        try write("dst/b.txt", "recente")
        try FileManager.default.setAttributes([.modificationDate: old], ofItemAtPath: root.appendingPathComponent("src/b.txt").path)
        conflictAnswer = .policy(.overwriteOlder)
        run(TransferJob(kind: .copy, sources: [root.appendingPathComponent("src/a.txt"), root.appendingPathComponent("src/b.txt")], destination: root.appendingPathComponent("dst")))
        XCTAssertEqual(read("dst/a.txt"), "nuovo")
        XCTAssertEqual(read("dst/b.txt"), "recente")
        XCTAssertEqual(conflicts, 1)
    }

    func testVerify() throws {
        try write("src/a.txt", "A")
        run(TransferJob(kind: .copy, sources: [root.appendingPathComponent("src/a.txt")], destination: root.appendingPathComponent("dst"), verify: true))
        XCTAssertEqual(read("dst/a.txt"), "A")
        XCTAssertTrue(errors.isEmpty)
    }

    func testDelete() throws {
        try write("x/a.txt", "A")
        run(TransferJob(kind: .delete, sources: [root.appendingPathComponent("x")]))
        XCTAssertFalse(FileManager.default.fileExists(atPath: root.appendingPathComponent("x").path))
    }

    func testSortFoldersFirst() {
        let items = [
            FileItem(url: URL(fileURLWithPath: "/b.txt"), name: "b.txt", isDirectory: false, size: 1),
            FileItem(url: URL(fileURLWithPath: "/Z"), name: "Z", isDirectory: true),
            FileItem(url: URL(fileURLWithPath: "/a.txt"), name: "a.txt", isDirectory: false, size: 9),
            FileItem(url: URL(fileURLWithPath: "/file10"), name: "file10", isDirectory: false),
            FileItem(url: URL(fileURLWithPath: "/file9"), name: "file9", isDirectory: false),
        ]
        let s = DirectoryLister.sorted(items, by: FileSort(key: .name, ascending: true)).map(\.name)
        XCTAssertEqual(s, ["Z", "a.txt", "b.txt", "file9", "file10"])
        let bySize = DirectoryLister.sorted(items, by: FileSort(key: .size, ascending: false)).map(\.name)
        XCTAssertEqual(bySize.first, "Z")
        XCTAssertEqual(bySize[1], "a.txt")
    }

    func testSortFoldersAlwaysOnTop() {
        let items = [
            FileItem(url: URL(fileURLWithPath: "/big.zip"), name: "big.zip", isDirectory: false, size: 900, modified: Date(timeIntervalSince1970: 9)),
            FileItem(url: URL(fileURLWithPath: "/A"), name: "A", isDirectory: true, modified: Date(timeIntervalSince1970: 1)),
            FileItem(url: URL(fileURLWithPath: "/B"), name: "B", isDirectory: true, modified: Date(timeIntervalSince1970: 2)),
        ]
        for key in [SortKey.name, .ext, .size, .date] {
            for asc in [true, false] {
                let s = DirectoryLister.sorted(items, by: FileSort(key: key, ascending: asc)).map(\.name)
                XCTAssertEqual(s.last, "big.zip", "\(key) \(asc)")
            }
        }
        // Dopo Option+Shift+Invio le cartelle si ordinano per dimensione calcolata.
        let sizes: [String: Int64] = ["/A": 10, "/B": 500]
        let s = DirectoryLister.sorted(items, by: FileSort(key: .size, ascending: false)) { sizes[$0.path] }.map(\.name)
        XCTAssertEqual(s, ["B", "A", "big.zip"])
    }

    func testFolderSymbol() {
        XCTAssertEqual(FolderSymbol.parse(Data(#"{"sym":"camera.fill"}"#.utf8)), .symbol("camera.fill"))
        XCTAssertEqual(FolderSymbol.parse(Data(#"{"emoji":"🎸"}"#.utf8)), .emoji("🎸"))
        XCTAssertNil(FolderSymbol.parse(Data("x".utf8)))
    }
}

final class MultiRenameTests: XCTestCase {
    private func rename(_ name: String, _ configure: (inout MultiRenameSettings) -> Void, index: Int = 0, total: Int = 1,
                        modified: Date? = nil, exif: Date? = nil, dir: String = "/Users/x/Foto/Vacanze") -> String {
        var s = MultiRenameSettings()
        configure(&s)
        let src = RenameSource(url: URL(fileURLWithPath: dir).appendingPathComponent(name), modified: modified, exifDate: exif)
        switch MultiRename.newName(for: src, index: index, settings: s, context: MultiRenameContext(total: total)) {
        case .success(let n): return n
        case .failure(let e): return "ERR: \(e)"
        }
    }

    private let date = DateComponents(calendar: Calendar(identifier: .gregorian), year: 2022, month: 6, day: 13, hour: 12, minute: 43, second: 5).date!

    func testDefaultKeepsName() {
        XCTAssertEqual(rename("IMG_0001.JPG", { _ in }), "IMG_0001.JPG")
    }

    func testPaoloTemplates() {
        XCTAssertEqual(rename("IMG_0001.JPG", { $0.nameMask = "[Y]-[M]-[D] [hms] - [N]" }, modified: date), "2022-06-13 124305 - IMG_0001.JPG")
        XCTAssertEqual(rename("a.jpg", { $0.nameMask = "[YMD]" }, modified: date), "20220613.jpg")
        XCTAssertEqual(rename("2022-06-13 124305 - Aperitivo.jpg", { $0.nameMask = "[N1-19] Dublino" }), "2022-06-13 124305 - Dublino.jpg")
    }

    func testRanges() {
        let n = "abcdefghij.txt"
        XCTAssertEqual(rename(n, { $0.nameMask = "[N1]" }), "a.txt")
        XCTAssertEqual(rename(n, { $0.nameMask = "[N2-5]" }), "bcde.txt")
        XCTAssertEqual(rename(n, { $0.nameMask = "[N2,3]" }), "bcd.txt")
        XCTAssertEqual(rename(n, { $0.nameMask = "[N8-]" }), "hij.txt")
        XCTAssertEqual(rename(n, { $0.nameMask = "[N-3-]" }), "hij.txt")
        XCTAssertEqual(rename(n, { $0.nameMask = "[N-3,2]" }), "hi.txt")
        XCTAssertEqual(rename(n, { $0.nameMask = "[N2--2]" }), "bcdefghi.txt")
        XCTAssertEqual(rename("abc.txt", { $0.nameMask = "[N02-9]" }), "000000bc.txt")
        XCTAssertEqual(rename("abc.txt", { $0.nameMask = "[P]_[N]" }), "Vacanze_abc.txt")
        XCTAssertEqual(rename("abc.txt", { $0.nameMask = "[G]-[N]" }), "Foto-abc.txt")
    }

    func testCounter() {
        XCTAssertEqual(rename("a.jpg", { $0.nameMask = "Foto [C]"; $0.counterDigits = 3 }, index: 4, total: 10), "Foto 005.jpg")
        XCTAssertEqual(rename("a.jpg", { $0.nameMask = "[C10+5:3]" }, index: 2), "020.jpg")
        XCTAssertEqual(rename("a.jpg", { $0.nameMask = "[C:a]" }, index: 0, total: 120), "001.jpg")
        XCTAssertEqual(rename("a.jpg", { $0.nameMask = "[Caa+1]" }, index: 27), "bb.jpg")
    }

    func testSearchReplace() {
        XCTAssertEqual(rename("Serie_s01e05_ITA.mkv", { $0.search = "_"; $0.replace = " " }), "Serie s01e05 ITA.mkv")
        XCTAssertEqual(rename("Serie.s01e05.mkv", { $0.search = "."; $0.replace = " "; $0.includeExtension = false }), "Serie s01e05.mkv")
        XCTAssertEqual(rename("Serie s01e05.mkv", { $0.search = "S01E"; $0.replace = "1x" }), "Serie 1x05.mkv")
        XCTAssertEqual(rename("Serie s01e05.mkv", { $0.search = "S01E"; $0.replace = "1x"; $0.caseSensitive = true }), "Serie s01e05.mkv")
        XCTAssertEqual(rename("città è.txt", { $0.search = "à|è"; $0.replace = "a|e" }), "citta e.txt")
        XCTAssertEqual(rename("a-a-a.txt", { $0.search = "a"; $0.replace = "b"; $0.firstOnly = true }), "b-a-a.txt")
        XCTAssertEqual(rename("Film (2020) [HD].mkv", { $0.search = " (*)"; $0.replace = "" }), "Film [HD].mkv")
        XCTAssertEqual(rename("Show.S02E03.720p.mkv", { $0.search = "S(\\d+)E(\\d+)"; $0.replace = "$1x$2"; $0.regex = true }), "Show.02x03.720p.mkv")
    }

    func testCase() {
        XCTAssertEqual(rename("il signore degli anelli.mkv", { $0.caseMode = .eachWordUpper }), "Il Signore Degli Anelli.mkv")
        XCTAssertEqual(rename("the lord of the rings.mkv", { $0.caseMode = .englishTitle; $0.includeExtension = false }), "The Lord of the Rings.mkv")
        XCTAssertEqual(rename("Abc.TXT", { $0.nameMask = "[U][N]"; $0.extMask = "[L][E]" }), "ABC.txt")
    }

    func testExifSwitch() {
        XCTAssertEqual(rename("a.jpg", { $0.nameMask = "[T4][YMD]" }, modified: Date(), exif: date), "20220613.jpg")
        // Senza EXIF il file resta com'è.
        XCTAssertEqual(rename("a.jpg", { $0.nameMask = "[T4][YMD]" }, modified: Date(), exif: nil), "a.jpg")
    }

    func testErrors() {
        XCTAssertTrue(rename("a.jpg", { $0.nameMask = "[Q]" }).hasPrefix("ERR"))
        XCTAssertTrue(rename("a.jpg", { $0.nameMask = "[N" }).hasPrefix("ERR"))
        XCTAssertEqual(rename("a.jpg", { $0.nameMask = "[[][N][]]" }), "[a].jpg")
    }
}

final class RenameExecutorTests: XCTestCase {
    func testSwapAndSubfolderAndConflicts() throws {
        let root = FileManager.default.temporaryDirectory.appendingPathComponent("mc-mrt-\(UUID().uuidString)")
        try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
        defer { try? FileManager.default.removeItem(at: root) }
        for n in ["a.txt", "b.txt", "c.txt", "x.txt"] { try n.write(to: root.appendingPathComponent(n), atomically: true, encoding: .utf8) }
        let ops = [
            RenameOperation(from: root.appendingPathComponent("a.txt"), to: root.appendingPathComponent("b.txt")),
            RenameOperation(from: root.appendingPathComponent("b.txt"), to: root.appendingPathComponent("a.txt")),
            RenameOperation(from: root.appendingPathComponent("c.txt"), to: root.appendingPathComponent("sub/c.txt")),
        ]
        XCTAssertTrue(RenameExecutor.conflicts(ops).isEmpty)
        let r = RenameExecutor.execute(ops)
        XCTAssertEqual(r.done.count, 3)
        XCTAssertEqual(try String(contentsOf: root.appendingPathComponent("a.txt"), encoding: .utf8), "b.txt")
        XCTAssertEqual(try String(contentsOf: root.appendingPathComponent("sub/c.txt"), encoding: .utf8), "c.txt")

        let clash = [RenameOperation(from: root.appendingPathComponent("a.txt"), to: root.appendingPathComponent("x.txt"))]
        XCTAssertEqual(RenameExecutor.conflicts(clash).count, 1)
        XCTAssertEqual(RenameExecutor.autoResolve(clash).first?.to.lastPathComponent, "x (2).txt")
    }
}

final class MultiRenameTemplateTests: XCTestCase {
    func testZeroStartLikePaoloTemplates() {
        var s = MultiRenameSettings()
        s.nameMask = "[N 0-19] Dublino [N 29-31]"
        let src = RenameSource(url: URL(fileURLWithPath: "/x/2023-08-15 101112 - IMG_20230815_101.jpg"))
        let r = try? MultiRename.newName(for: src, index: 0, settings: s, context: MultiRenameContext(total: 1)).get()
        XCTAssertEqual(r, "2023-08-15 101112 - Dublino 081.jpg")
    }
}

final class FtpTests: XCTestCase, TransferEngineDelegate {
    func engine(_ engine: TransferControl, progress: TransferProgress) {}
    func engine(_ engine: TransferControl, conflictAt destination: URL, source: URL) -> ConflictChoice { .overwrite }
    func engine(_ engine: TransferControl, error: Error, at url: URL) -> ErrorChoice { XCTFail("\(error)"); return .skip }
    func engine(_ engine: TransferControl, trashFailedFor url: URL, error: Error) -> TrashFallback { .skip }

    func testListParsers() {
        let unix = """
        total 8
        drwxr-xr-x    2 web  web      4096 Mar  3 10:15 css
        -rw-r--r--    1 web  web       123 Jan 12  2023 nome con spazi.txt
        lrwxrwxrwx    1 web  web        11 Feb  1 09:00 link -> target
        """
        let u = FtpListParser.parseLIST(Data(unix.utf8))
        XCTAssertEqual(u.map(\.name), ["css", "nome con spazi.txt", "link"])
        XCTAssertTrue(u[0].isDirectory)
        XCTAssertEqual(u[1].size, 123)
        XCTAssertTrue(u[2].isLink)
        let win = "01-31-23  10:00AM       <DIR>          images\r\n02-15-23  03:30PM               2048 index.html\r\n"
        let w = FtpListParser.parseLIST(Data(win.utf8))
        XCTAssertEqual(w.map(\.name), ["images", "index.html"])
        XCTAssertTrue(w[0].isDirectory)
        let mlsd = "type=cdir;modify=20230101000000; .\r\ntype=dir;modify=20230101120000; css\r\ntype=file;size=42;modify=20230615123045; index.html\r\n"
        let m = FtpListParser.parseMLSD(Data(mlsd.utf8))
        XCTAssertEqual(m.map(\.name), ["css", "index.html"])
        XCTAssertEqual(m[1].size, 42)
        XCTAssertNotNil(m[1].modified)
    }

    func testTCImport() {
        let ini = """
        [connections]
        1=Cliente Uno
        [Cliente Uno]
        host=ftps://ftp.cliente.it
        username=utente
        directory=/public_html
        localdir=D:\\Lavoro\\Siti Web\\cliente\\
        pasvmode=1
        [Altro]
        host=ftp.altro.it:2121
        localdir=c:\\temp
        [General]
        x=1
        """
        let r = TCFtpImport.parse(ini, withPasswords: false)
        XCTAssertEqual(r.count, 2)
        XCTAssertEqual(r[0].connection.host, "ftp.cliente.it")
        XCTAssertTrue(r[0].connection.tls)
        XCTAssertEqual(r[0].connection.localDir, "~/Server/Siti Web/cliente/")
        XCTAssertEqual(r[1].connection.host, "ftp.altro.it:2121")
        XCTAssertEqual(r[1].connection.localDir, "")
        XCTAssertNil(TCPassword.decode("zz"))
    }

    /// Prova vera contro un server FTP locale (MC_FTP_TEST=1, porta 2121, utente prova/segreta).
    func testLiveServer() throws {
        guard ProcessInfo.processInfo.environment["MC_FTP_TEST"] == "1" else { throw XCTSkip("server FTP di prova non attivo") }
        var c = FtpConnection(name: "prova", host: "127.0.0.1:2121")
        c.user = "prova"
        let s = FtpSession(connection: c, password: "segreta")
        let root = try s.list("/sito")
        XCTAssertEqual(Set(root.map(\.name)), ["css", "index.html", "nome con spazi.txt"])
        let tmp = FileManager.default.temporaryDirectory.appendingPathComponent("mc-ftp-\(UUID().uuidString)")
        try FileManager.default.createDirectory(at: tmp, withIntermediateDirectories: true)
        defer { try? FileManager.default.removeItem(at: tmp) }
        try s.download("/sito/nome con spazi.txt", to: tmp.appendingPathComponent("a.txt")) { _ in true }
        XCTAssertEqual(try String(contentsOf: tmp.appendingPathComponent("a.txt"), encoding: .utf8), "file con spazi\n")
        try "nuovo".write(to: tmp.appendingPathComponent("su.txt"), atomically: true, encoding: .utf8)
        try s.upload(tmp.appendingPathComponent("su.txt"), to: "/sito/nuova cartella/su.txt") { _ in true }
        try s.rename("/sito/nuova cartella/su.txt", to: "/sito/nuova cartella/giù.txt")
        XCTAssertEqual(try s.list("/sito/nuova cartella").map(\.name), ["giù.txt"])
        try s.deleteRecursively("/sito/nuova cartella", isDirectory: true)
        XCTAssertFalse(try s.list("/sito").map(\.name).contains("nuova cartella"))

        // Coda: scarica la cartella intera, poi la ricarica con un altro nome.
        let id = FtpRegistry.register(s)
        let remoteSito = FtpRegistry.url(id: id, path: "/sito")
        var job = TransferJob(kind: .copy, sources: [remoteSito], destination: tmp)
        job.directorySources = [remoteSito]
        let t = FtpTransfer()
        t.delegate = self
        t.run(job)
        XCTAssertEqual(try String(contentsOf: tmp.appendingPathComponent("sito/css/style.css"), encoding: .utf8), "body{}\n")
        let up = TransferJob(kind: .copy, sources: [tmp.appendingPathComponent("sito")], destination: FtpRegistry.url(id: id, path: "/"), newName: "copia")
        let t2 = FtpTransfer()
        t2.delegate = self
        t2.run(up)
        XCTAssertEqual(Set(try s.list("/copia").map(\.name)), ["css", "index.html", "nome con spazi.txt"])
        try s.deleteRecursively("/copia", isDirectory: true)
    }
}

final class FileDatesTests: XCTestCase {
    private let cal = Calendar(identifier: .gregorian)
    private func d(_ y: Int, _ m: Int, _ day: Int, _ h: Int = 12, _ min: Int = 0, _ s: Int = 0) -> Date {
        cal.date(from: DateComponents(year: y, month: m, day: day, hour: h, minute: min, second: s))!
    }

    func testCopyFromModified() {
        var s = DateChangeSettings()
        s.copyFrom = .modified
        s.copyTo = [.created, .accessed]
        let old = FileDates(created: d(2019, 5, 15, 11, 56, 5), modified: d(2000, 6, 24), accessed: d(2026, 2, 1))
        let n = DateChanger.newDates(old, index: 0, settings: s)
        XCTAssertEqual(n.created, d(2000, 6, 24))
        XCTAssertEqual(n.accessed, d(2000, 6, 24))
        XCTAssertEqual(n.modified, d(2000, 6, 24))
    }

    func testSetTimeAndAddSequence() {
        var s = DateChangeSettings()
        s.fields[.modified]!.setTime = true
        s.fields[.modified]!.time = d(2000, 1, 1, 9, 30, 0)
        s.fields[.modified]!.add = true
        s.fields[.modified]!.amount = 1
        s.fields[.modified]!.step = .minutes
        s.sequence = true
        let old = FileDates(modified: d(2000, 6, 24, 12, 0, 0))
        XCTAssertEqual(DateChanger.newDates(old, index: 0, settings: s).modified, d(2000, 6, 24, 9, 30, 0))
        XCTAssertEqual(DateChanger.newDates(old, index: 2, settings: s).modified, d(2000, 6, 24, 9, 32, 0))
    }

    func testAddHoursAndApplyOnDisk() throws {
        var s = DateChangeSettings()
        s.fields[.modified]!.add = true
        s.fields[.modified]!.amount = -7
        s.copyFrom = .modified
        s.copyTo = [.created]
        let url = FileManager.default.temporaryDirectory.appendingPathComponent("mc-date-\(UUID().uuidString).txt")
        try "x".write(to: url, atomically: true, encoding: .utf8)
        defer { try? FileManager.default.removeItem(at: url) }
        try FileManager.default.setAttributes([.modificationDate: d(2000, 6, 24, 12)], ofItemAtPath: url.path)
        let old = FileDates.read(url)
        let new = DateChanger.newDates(old, index: 0, settings: s)
        try DateChanger.apply(url, from: old, to: new, hidden: .unchanged, locked: .unchanged)
        let after = FileDates.read(url)
        XCTAssertEqual(after.modified?.timeIntervalSince1970 ?? 0, d(2000, 6, 24, 5).timeIntervalSince1970, accuracy: 1)
        XCTAssertEqual(after.created?.timeIntervalSince1970 ?? 0, d(2000, 6, 24, 5).timeIntervalSince1970, accuracy: 1)
    }
}
