"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const child_process_1 = tslib_1.__importDefault(require("child_process"));
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
const http_1 = tslib_1.__importDefault(require("http"));
const path_1 = tslib_1.__importDefault(require("path"));
const morgan_1 = tslib_1.__importDefault(require("morgan"));
const express_1 = tslib_1.__importDefault(require("express"));
const socket_io_1 = tslib_1.__importDefault(require("socket.io"));
const constants_1 = require("./constants");
const collection_1 = require("./utils/collection");
const git_1 = require("./utils/git");
const workspace = process.env.TUTURE_PATH || process.cwd();
const diffPath = path_1.default.join(workspace, constants_1.DIFF_PATH);
const makeServer = (config) => {
    const app = express_1.default();
    const server = http_1.default.createServer(app);
    // Socket.IO server instance.
    const io = socket_io_1.default(server);
    if (process.env.NODE_ENV === 'development') {
        app.use(morgan_1.default('dev'));
    }
    app.use(express_1.default.json({ limit: '50mb' }));
    app.use(express_1.default.urlencoded({ extended: false }));
    app.use('/static', express_1.default.static(constants_1.EDITOR_STATIC_PATH));
    app.get('/diff', (_, res) => {
        res.json(JSON.parse(fs_extra_1.default.readFileSync(diffPath).toString()));
    });
    app.get('/collection', (_, res) => {
        res.json(collection_1.loadCollection());
    });
    app.get('/remotes', (_, res) => {
        git_1.git
            .getRemotes(true)
            .then((remotes) => res.json(remotes))
            .catch((err) => res.status(500).json(err));
    });
    app.post('/save', (req, res) => {
        collection_1.saveCollection(req.body);
        res.sendStatus(200);
    });
    app.get('/sync', async (req, res) => {
        child_process_1.default.execFile('tuture', ['sync'], {}, (err) => {
            if (err) {
                res.status(500).json({ exitCode: err.code });
            }
            else {
                res.sendStatus(200);
            }
        });
    });
    app.get('/reload', (_, res) => {
        io.emit('reload');
        res.sendStatus(200);
    });
    app.get('*', (_, res) => {
        const html = fs_extra_1.default
            .readFileSync(path_1.default.join(constants_1.EDITOR_PATH, 'index.html'))
            .toString();
        res.send(html);
    });
    return app;
};
exports.default = makeServer;
