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 testHotlistAccessKey() {
        let e = HotlistEntry(name: "Down&loads", path: "~/Downloads")
        XCTAssertEqual(e.title, "Downloads")
        XCTAssertEqual(e.accessKey, "l")
        XCTAssertEqual(e.url?.path, NSHomeDirectory() + "/Downloads")
    }
}

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: TransferEngine, progress done: Int64, of total: Int64, current: String) {}
    func engine(_ engine: TransferEngine, conflictAt destination: URL, source: URL) -> ConflictChoice {
        conflicts += 1
        return conflictAnswer
    }
    func engine(_ engine: TransferEngine, error: Error, at url: URL) -> ErrorChoice {
        errors.append(error.localizedDescription)
        return .skip
    }
    func engine(_ engine: TransferEngine, 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)")
    }

    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 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: SortOrder(key: .name, ascending: true)).map(\.name)
        XCTAssertEqual(s, ["Z", "a.txt", "b.txt", "file9", "file10"])
        let bySize = DirectoryLister.sorted(items, by: SortOrder(key: .size, ascending: false)).map(\.name)
        XCTAssertEqual(bySize.first, "Z")
        XCTAssertEqual(bySize[1], "a.txt")
    }
}
