"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.disable = exports.enable = exports.run = exports.getAll = void 0;
const lodash_1 = __importDefault(require("lodash"));
const constraints_1 = __importDefault(require("../validation/constraints"));
const errorTypes_1 = __importDefault(require("../utils/errorTypes"));
const Resources = __importStar(require("../utils/resources"));
const scheduler_1 = require("../jobs/scheduler");
const strings_1 = require("../utils/strings");
const validator_1 = require("../validation/validator");
const isValidId = validator_1.forConstraint(constraints_1.default.id, false);
function toExternalTask(task) {
    return {
        id: task.id,
        name: task.name,
        description: task.description,
        schedule: task.schedule,
        runningSince: task.runningSince && task.runningSince.unix(),
        lastRunStarted: task.lastRunStarted && task.lastRunStarted.unix(),
        lastRunDuration: task.lastRunDuration || null,
        state: task.state,
        result: task.state !== scheduler_1.TaskState.RUNNING && task.result ? task.result.state : null,
        message: task.state !== scheduler_1.TaskState.RUNNING && task.result ? task.result.message || null : null,
        enabled: task.enabled
    };
}
async function withValidTaskId(req) {
    const id = strings_1.normalizeString(Resources.getData(req).id);
    if (!isValidId(id)) {
        throw { data: 'Invalid task id.', type: errorTypes_1.default.badRequest };
    }
    return id;
}
async function getTask(id) {
    const tasks = scheduler_1.getTasks();
    const task = tasks[id];
    if (!task) {
        throw { data: 'Task not found.', type: errorTypes_1.default.notFound };
    }
    return task;
}
async function withTask(req) {
    const id = await withValidTaskId(req);
    return await getTask(id);
}
function setTaskEnabled(req, res, enable) {
    withTask(req)
        .then(task => {
        task.enabled = enable;
        Resources.success(res, toExternalTask(task));
    })
        .catch(err => Resources.error(res, err));
}
async function doGetAll(req) {
    const restParams = await Resources.getValidRestParams('list', null, req);
    const tasks = Resources.sort(lodash_1.default.values(scheduler_1.getTasks()), ['id', 'name', 'schedule', 'state', 'runningSince', 'lastRunStarted'], restParams);
    const filteredTasks = Resources.filter(tasks, ['id', 'name', 'schedule', 'state'], restParams);
    const total = filteredTasks.length;
    const pageTasks = Resources.getPageEntities(filteredTasks, restParams);
    return {
        total,
        pageTasks,
    };
}
function getAll(req, res) {
    doGetAll(req)
        .then(({ total, pageTasks }) => {
        res.set('X-Total-Count', total.toString(10));
        Resources.success(res, lodash_1.default.map(pageTasks, toExternalTask));
    })
        .catch(err => Resources.error(res, err));
}
exports.getAll = getAll;
function run(req, res) {
    withTask(req)
        .then(task => {
        if (task.runningSince) {
            return Resources.error(res, { data: 'Task already running.', type: errorTypes_1.default.conflict });
        }
        task.run();
        Resources.success(res, toExternalTask(task));
    })
        .catch(err => Resources.error(res, err));
}
exports.run = run;
function enable(req, res) {
    setTaskEnabled(req, res, true);
}
exports.enable = enable;
function disable(req, res) {
    setTaskEnabled(req, res, false);
}
exports.disable = disable;
//# sourceMappingURL=taskResource.js.map