import AppKit
import CommanderCore

/// Una sola coda: copie e spostamenti vanno uno dopo l'altro, mai in parallelo.
/// Le eliminazioni hanno una loro coda, così non aspettano dietro una copia lunga.
final class TransferQueue: TransferEngineDelegate {
    private(set) var pending: [TransferJob] = []
    private(set) var current: TransferJob?
    private(set) var engine: TransferControl?
    private let worker = DispatchQueue(label: "mac-commander.transfers")
    private let deleter = DispatchQueue(label: "mac-commander.deletes")

    private(set) var progress = TransferProgress()
    private var lastUpdate = Date.distantPast
    private let updateLock = NSLock()

    private(set) var paused = false
    /// Come in TC: limite in kB/s, attivo o no.
    var speedLimitEnabled = UserDefaults.standard.bool(forKey: "coda.limiteAttivo") {
        didSet { UserDefaults.standard.set(speedLimitEnabled, forKey: "coda.limiteAttivo"); applyLimit() }
    }
    var speedLimitKB: Double = UserDefaults.standard.object(forKey: "coda.limiteKB") as? Double ?? 5.0 {
        didSet { UserDefaults.standard.set(speedLimitKB, forKey: "coda.limiteKB"); applyLimit() }
    }

    var onChange: (() -> Void)?
    var onJobFinished: ((TransferJob) -> Void)?

    var isBusy: Bool { current != nil || !pending.isEmpty }

    func enqueue(_ job: TransferJob) {
        if job.kind == .trash || job.kind == .delete {
            let e = TransferEngine()
            e.delegate = self
            deleter.async {
                e.run(job)
                DispatchQueue.main.async { self.onJobFinished?(job) }
            }
            return
        }
        pending.append(job)
        startNextIfIdle()
        onChange?()
    }

    func setPaused(_ p: Bool) {
        paused = p
        engine?.setPaused(p)
        onChange?()
    }

    /// Annulla: ferma quella in corso e svuota la coda.
    func cancelAll() {
        pending.removeAll()
        engine?.cancel()
        onChange?()
    }

    private func applyLimit() {
        engine?.setSpeedLimit(speedLimitEnabled ? Int64(speedLimitKB * 1024) : nil)
    }

    // MARK: - Elenco come nella finestra di TC

    struct Entry: Equatable {
        enum Where: Equatable { case running, remaining, pending(UUID) }
        let place: Where
        let kind: TransferKind
        let source: URL
        let destination: URL?

        var text: String {
            let verb = kind == .move ? "move" : kind == .pack ? "pack" : kind == .extract ? "unpack" : "copy"
            return "\(verb):\(Format.path(source)) -> \(destination.map(Format.path) ?? "")"
        }
    }

    var entries: [Entry] {
        var list: [Entry] = []
        if let job = current {
            if let s = progress.source {
                list.append(Entry(place: .running, kind: job.kind, source: s, destination: progress.destination))
            }
            for r in engine?.remaining ?? [] {
                list.append(Entry(place: .remaining, kind: job.kind, source: r.src, destination: r.dst))
            }
        }
        for job in pending {
            for s in job.sources {
                let dst = job.destination?.appendingPathComponent(job.targetName(for: s))
                list.append(Entry(place: .pending(job.id), kind: job.kind, source: s, destination: dst))
            }
        }
        return list
    }

    /// Il tasto "-": toglie dalla coda un elemento non ancora iniziato.
    func remove(_ entry: Entry) {
        switch entry.place {
        case .running:
            NSSound.beep()
        case .remaining:
            engine?.skip(entry.source)
        case .pending(let id):
            guard let i = pending.firstIndex(where: { $0.id == id }) else { return }
            pending[i].sources.removeAll { $0 == entry.source }
            if pending[i].sources.isEmpty { pending.remove(at: i) }
        }
        onChange?()
    }

    private func startNextIfIdle() {
        guard current == nil, !pending.isEmpty else { return }
        let job = pending.removeFirst()
        let isFtp = (job.destination.map(FtpRegistry.isRemote) ?? false) || job.sources.contains(where: FtpRegistry.isRemote)
        let e: TransferControl
        if ArchiveTransfer.handles(job) { e = ArchiveTransfer() } else if isFtp { e = FtpTransfer() } else {
            let te = TransferEngine()
            te.keepDates = Settings.shared.keepDates
            e = te
        }
        e.delegate = self
        e.setPaused(paused)
        current = job
        engine = e
        applyLimit()
        progress = TransferProgress()
        worker.async {
            e.run(job)
            DispatchQueue.main.async {
                self.current = nil
                self.engine = nil
                self.onJobFinished?(job)
                self.startNextIfIdle()
                self.onChange?()
            }
        }
    }

    // MARK: - TransferEngineDelegate (thread di lavoro)

    func engine(_ engine: TransferControl, progress p: TransferProgress) {
        updateLock.lock()
        let now = Date()
        let due = p.done >= p.total || now.timeIntervalSince(lastUpdate) > 0.1
        if due { lastUpdate = now }
        updateLock.unlock()
        guard due else { return }
        DispatchQueue.main.async {
            guard engine === self.engine else { return }
            self.progress = p
            self.onChange?()
        }
    }

    func engine(_ engine: TransferControl, conflictAt destination: URL, source: URL) -> ConflictChoice {
        DispatchQueue.main.sync { ConflictDialog.run(destination: destination, source: source) }
    }

    func engine(_ engine: TransferControl, error: Error, at url: URL) -> ErrorChoice {
        DispatchQueue.main.sync { Dialogs.error(error, at: url) }
    }

    func engine(_ engine: TransferControl, trashFailedFor url: URL, error: Error) -> TrashFallback {
        DispatchQueue.main.sync { Dialogs.trashFailed(url, error: error) }
    }
}

/// La finestra della coda, come quella di TC: resta aperta durante la copia,
/// con due barre (file e totale), l'elenco, "-", Pausa e limite di velocità.
final class QueueWindowController: NSWindowController, NSWindowDelegate, NSTableViewDataSource, NSTableViewDelegate {
    private let queue: TransferQueue
    private let currentLabel = NSTextField(labelWithString: "")
    private let fileBar = NSProgressIndicator()
    private let totalBar = NSProgressIndicator()
    private let filePct = NSTextField(labelWithString: "0%")
    private let totalPct = NSTextField(labelWithString: "0%")
    private let table = NSTableView()
    private var rows: [TransferQueue.Entry] = []
    private var pauseButton: ActionButton!
    private let limitCheck = NSButton(checkboxWithTitle: "Limite di velocità", target: nil, action: nil)
    private let limitField = NSTextField(string: "")
    /// Il tasto "+": apre F5 per aggiungere i file selezionati.
    var onAdd: (() -> Void)?

    init(queue: TransferQueue) {
        self.queue = queue
        let panel = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 900, height: 300),
                            styleMask: [.titled, .closable, .resizable, .miniaturizable], backing: .buffered, defer: false)
        panel.becomesKeyOnlyIfNeeded = true
        panel.isReleasedWhenClosed = false
        panel.hidesOnDeactivate = false
        panel.isFloatingPanel = false
        panel.minSize = NSSize(width: 500, height: 200)
        super.init(window: panel)
        panel.delegate = self
        build()
        if !panel.setFrameUsingName("Coda") { panel.centerInApp() }
        panel.setFrameAutosaveName("Coda")
    }

    required init?(coder: NSCoder) { fatalError() }

    private func build() {
        for b in [fileBar, totalBar] {
            b.style = .bar
            b.isIndeterminate = false
            b.minValue = 0
            b.maxValue = 1
        }
        currentLabel.lineBreakMode = .byTruncatingMiddle
        currentLabel.alignment = .left
        currentLabel.font = Theme.font
        for l in [filePct, totalPct] {
            l.font = Theme.digits
            l.alignment = .right
            l.widthAnchor.constraint(equalToConstant: 44).isActive = true
        }
        let col = NSTableColumn(identifier: NSUserInterfaceItemIdentifier("voce"))
        col.resizingMask = .autoresizingMask
        table.addTableColumn(col)
        table.headerView = nil
        table.dataSource = self
        table.delegate = self
        table.rowHeight = 18
        table.columnAutoresizingStyle = .firstColumnOnlyAutoresizingStyle
        let scroll = NSScrollView()
        scroll.documentView = table
        scroll.hasVerticalScroller = true
        scroll.borderType = .bezelBorder

        let plus = ActionButton("+") { [weak self] in self?.onAdd?() }
        plus.toolTip = "Aggiunge alla coda i file selezionati nel pannello (come F5 + F2)"
        let minus = ActionButton("-") { [weak self] in self?.removeSelected() }
        minus.toolTip = "Togli dalla coda"
        pauseButton = ActionButton("Pausa") { [weak self] in
            guard let self else { return }
            self.queue.setPaused(!self.queue.paused)
        }
        limitCheck.target = self
        limitCheck.action = #selector(limitChanged)
        limitCheck.state = queue.speedLimitEnabled ? .on : .off
        limitField.stringValue = String(format: "%.1f", queue.speedLimitKB).replacingOccurrences(of: ".", with: ",")
        limitField.target = self
        limitField.action = #selector(limitChanged)
        limitField.widthAnchor.constraint(equalToConstant: 70).isActive = true
        let cancel = ActionButton("Annulla") { [weak self] in self?.confirmCancel() }
        let spacer = NSView()
        spacer.setContentHuggingPriority(.init(1), for: .horizontal)
        let bottom = NSStackView(views: [plus, minus, pauseButton, limitCheck, limitField, NSTextField(labelWithString: "kB/s"), spacer, cancel])
        bottom.orientation = .horizontal
        bottom.spacing = 8

        let fileRow = NSStackView(views: [fileBar, filePct])
        let totalRow = NSStackView(views: [totalBar, totalPct])
        let views: [NSView] = [currentLabel, fileRow, totalRow, scroll, bottom]
        let stack = NSStackView(views: views)
        stack.orientation = .vertical
        stack.alignment = .leading
        stack.spacing = 6
        stack.edgeInsets = NSEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
        for v in views { v.widthAnchor.constraint(equalTo: stack.widthAnchor, constant: -16).isActive = true }
        scroll.setContentHuggingPriority(.init(1), for: .vertical)
        window?.contentView = stack
    }

    func update() {
        guard let job = queue.current else {
            window?.orderOut(nil)
            return
        }
        let p = queue.progress
        let fileFrac = p.fileSize > 0 ? Double(p.fileDone) / Double(p.fileSize) : 0
        let totalFrac = p.total > 0 ? Double(p.done) / Double(p.total) : 0
        fileBar.doubleValue = fileFrac
        totalBar.doubleValue = totalFrac
        filePct.stringValue = "\(Int(fileFrac * 100))%"
        totalPct.stringValue = "\(Int(totalFrac * 100))%"
        let name = p.source?.lastPathComponent ?? ""
        currentLabel.stringValue = p.source == nil ? job.title : "\(name)->\(p.destination?.lastPathComponent ?? "")"
        let state = queue.paused ? "In pausa · " : ""
        window?.title = "\(state)\(Int(totalFrac * 100))% \(name) (\(job.kind.verb))"
        pauseButton.title = queue.paused ? "Riprendi" : "Pausa"

        let newRows = queue.entries
        if newRows != rows {
            let selected = table.selectedRow >= 0 && table.selectedRow < rows.count ? rows[table.selectedRow] : nil
            rows = newRows
            table.reloadData()
            if let selected, let i = rows.firstIndex(of: selected) {
                table.selectRowIndexes(IndexSet(integer: i), byExtendingSelection: false)
            }
        }
        if window?.isVisible == false {
            // Si apre senza togliere la tastiera ai pannelli.
            window?.orderFront(nil)
        }
    }

    private func removeSelected() {
        let r = table.selectedRow
        guard rows.indices.contains(r) else { NSSound.beep(); return }
        queue.remove(rows[r])
    }

    private func confirmCancel() {
        guard queue.isBusy else { return }
        if Dialogs.confirm("Interrompere la copia?", info: "Si ferma quella in corso e si svuota la coda.", ok: "Interrompi") {
            queue.cancelAll()
        }
    }

    @objc private func limitChanged() {
        let v = Double(limitField.stringValue.replacingOccurrences(of: ",", with: ".")) ?? queue.speedLimitKB
        queue.speedLimitKB = max(v, 0.1)
        queue.speedLimitEnabled = limitCheck.state == .on
    }

    func windowShouldClose(_ sender: NSWindow) -> Bool {
        confirmCancel()
        return !queue.isBusy
    }

    // MARK: - Tabella

    func numberOfRows(in tableView: NSTableView) -> Int { rows.count }

    func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
        let tf = (tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier("voce"), owner: self) as? NSTextField) ?? {
            let t = NSTextField(labelWithString: "")
            t.identifier = NSUserInterfaceItemIdentifier("voce")
            t.lineBreakMode = .byTruncatingMiddle
            t.font = NSFont.systemFont(ofSize: 12)
            return t
        }()
        tf.stringValue = rows[row].text
        tf.textColor = rows[row].place == .running ? .controlAccentColor : .labelColor
        return tf
    }
}
