#!/usr/bin/env node
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const multer_1 = __importDefault(require("multer"));
const path_1 = require("path");
const node_os_1 = require("node:os");
const promises_1 = require("node:fs/promises");
const App_1 = __importDefault(require("./App"));
const ws_1 = require("ws");
const open = import("open");
const URI_1 = require("./utils/URI");
const types_1 = require("./types");
const commands_1 = require("./commands");
const commander_1 = require("commander");
const package_json_1 = __importDefault(require("../package.json"));
const options_1 = __importDefault(require("./options"));
commander_1.program
    .name('F5')
    .description('SFTP/FTP client, dual-panel file manager in the browser')
    .version(package_json_1.default.version)
    .option('-p, --port <number>', 'port number', '3113')
    .option('--log', 'prints the log information');
commander_1.program.parse();
const inputOptions = commander_1.program.opts();
const port = inputOptions.port ?? 3113;
options_1.default.log = inputOptions.log ?? process.env.NODE_ENV == 'development';
const app = (0, express_1.default)();
app.use(express_1.default.json());
app.use(express_1.default.static((0, path_1.resolve)(__dirname, 'public')));
app.use(express_1.default.static((0, path_1.resolve)(__dirname, '../dist/public')));
const server = app.listen(port, async () => {
    console.log(`Listening on http://localhost:${port}`);
    if (process.env.NODE_ENV !== 'development') {
        (await open).default(`http://localhost:${port}`);
    }
});
const handle = async (name, handler) => {
    app.post(`/api/${name}`, async (req, res) => {
        try {
            const result = await handler(req.body);
            res.json(result ?? null);
        }
        catch (e) {
            res.status(400);
            process.env.NODE_ENV == 'development' && console.error(e);
            res.json({ message: (typeof e == 'object' && 'message' in e) ? e.message : String(e) });
        }
    });
};
const upload = (0, multer_1.default)({ dest: (0, node_os_1.tmpdir)() });
app.post('/api/upload', upload.array('files'), async function (req, res) {
    if (Array.isArray(req.files)) {
        const src = [];
        for (const { path, originalname } of req.files) {
            const fnm = (0, path_1.join)((0, path_1.dirname)(path), originalname);
            await (0, promises_1.rename)(path, fnm);
            src.push(fnm);
        }
        commands_1.commands.copy(src.map(path => (0, URI_1.createURI)(types_1.LocalFileSystemID, path)), req.body['to'], true, null, null, () => src.forEach(path => (0, promises_1.rm)(path, { force: true })));
    }
    res.json(true);
});
const wss = new ws_1.WebSocketServer({ server, path: `/events` });
const emitter = channel => event => wss.clients.forEach(ws => ws.send(JSON.stringify({ channel, ...event })));
App_1.default.bootstrap(handle, emitter, async (file) => { (await open).default(file); });
