"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = default_1;
const node_path_1 = require("node:path");
const URI_1 = require("../utils/URI");
const types_1 = require("../types");
const Queue_1 = require("../queues/Queue");
const Duplicate_1 = __importDefault(require("../queues/Duplicate"));
const uniqid_1 = __importDefault(require("../utils/uniqid"));
const App_1 = __importDefault(require("../App"));
function default_1(src, filter) {
    if (!src.length) {
        return;
    }
    const { id: connection } = (0, URI_1.parseURI)(src[0]);
    const targets = new Map();
    src.forEach(uri => {
        const { path } = (0, URI_1.parseURI)(uri);
        const parent = (0, node_path_1.dirname)(path);
        if (!targets.has(parent)) {
            targets.set(parent, []);
        }
        targets.get(parent).push(path);
    });
    for (const [to, from] of targets) {
        const id = (0, uniqid_1.default)();
        const queue = new Duplicate_1.default(connection, from, to, filter, state => App_1.default.onQueueUpdate(id, { type: types_1.QueueEventType.Update, state }), (from, to) => App_1.default.onQueueUpdate(id, { type: types_1.QueueEventType.Ask, queueType: types_1.QueueType.Copy, from, to }), error => {
            App_1.default.onError({
                type: types_1.FailureType.RemoteError,
                id: connection,
                message: error.message ?? String(error)
            });
        }, () => {
            Queue_1.queues.delete(id);
            App_1.default.onQueueUpdate(id, { type: types_1.QueueEventType.Complete });
        }, App_1.default.remoteWatcher);
        Queue_1.queues.set(id, queue);
        App_1.default.onQueueUpdate(id, { type: types_1.QueueEventType.Create, queueType: types_1.QueueType.Copy, connection });
        queue.create();
    }
}
