"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const node_path_1 = require("node:path");
const Queue_1 = __importDefault(require("./Queue"));
const types_1 = require("../types");
const URI_1 = require("../utils/URI");
class CopyQueue extends Queue_1.default {
    constructor(connId, src, dest, filter, onState, onConflict, onError, onComplete, watcher, move) {
        super(connId, connId, src, dest, filter, onState, onConflict, onComplete);
        this.onError = onError;
        this.watcher = watcher;
        this.move = move;
        this.touched = new Map();
    }
    async enqueue(paths, dest) {
        if (this.move) { // No filter
            const stat = this.stat(this.from);
            await Promise.all(paths
                .filter(path => path != dest && (0, node_path_1.dirname)(path) != dest)
                .map(async (path) => {
                const from = await stat(path);
                if (from) {
                    this.queue.push({
                        from,
                        dirs: [],
                        to: this.dest
                    });
                    this.totalCnt++;
                    this.totalSize++;
                }
            }));
        }
        else {
            await super.enqueue(paths, dest);
        }
    }
    async transmit(fs, from, dirs, to) {
        if (this.stopped) {
            return;
        }
        try {
            let p;
            if (this.move) {
                p = fs.mv(from.path, (0, node_path_1.join)(to, ...dirs, from.name));
                const parent = (0, node_path_1.dirname)(from.path);
                this.touched.set(parent, [...(this.touched.get(parent) ?? []), p]);
            }
            else {
                p = fs.cp(from.path, (0, node_path_1.join)(to, ...dirs, from.name), from.dir);
            }
            await p;
            this.touched.set(to, [...(this.touched.get(to) ?? []), p]);
        }
        catch (error) {
            this.onError(error);
        }
        this.sendState(from.size);
    }
    async finalize() {
        if (this.to != types_1.LocalFileSystemID) {
            await Promise.all(Array.from(this.touched.values()).flat());
            Array.from(this.touched.keys()).forEach(path => this.watcher.refresh((0, URI_1.createURI)(this.to, path)));
        }
    }
}
exports.default = CopyQueue;
