"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 Local_1 = require("../Local");
const URI_1 = require("../utils/URI");
class UploadQueue extends Queue_1.default {
    constructor(connId, src, dest, filter, onState, onConflict, onError, onComplete, watcher) {
        super(types_1.LocalFileSystemID, connId, src, dest, filter, onState, onConflict, onComplete);
        this.onError = onError;
        this.watcher = watcher;
        this.touched = new Map();
    }
    async transmit(fs, from, dirs, to) {
        if (this.stopped) {
            return;
        }
        if (!((0, Local_1.stat)(from.path))) {
            return;
        }
        try {
            let targetDir = to;
            for (const dir of dirs) {
                targetDir = (0, node_path_1.join)(targetDir, dir);
                if (this.touched.has(targetDir)) {
                    await this.touched.get(targetDir);
                }
                else {
                    this.touched.set(targetDir, new Promise(async (resolve) => {
                        try {
                            await fs.mkdir(targetDir);
                        }
                        catch (e) { }
                        resolve();
                    }));
                }
            }
            if (!this.stopped) {
                await fs.put(from.path, (0, node_path_1.join)(targetDir, from.name));
            }
        }
        catch (error) {
            this.onError(error);
        }
        this.sendState(from.size);
    }
    async finalize() {
        this.touched.set(this.dest, Promise.resolve());
        await Promise.all(Array.from(this.touched.values()));
        Array.from(this.touched.keys()).forEach(path => this.watcher.refresh((0, URI_1.createURI)(this.to, path)));
    }
}
exports.default = UploadQueue;
