const fetch = require('node-fetch');
const querystring = require('querystring');
const log = require('../common/log');

const STATES = [
    'free', 'in-progress', 'suspended',
    'failed', 'rollback', 'rollback-failed',
    'success', 'canceled'
];

const DEFAULT_STATES = [
    'free', 'in-progress', 'suspended',
    'failed', 'rollback', 'rollback-failed',
    'canceled'
];

function getTasks(req, res, options) {
    let states = STATES.filter(state => Boolean(req.query[state]));

    options = {
        state: (states.length ? states : DEFAULT_STATES).join(','),
        page: req.params.page,
        dependent_id: req.params.task_id,
        ordering: '-created_at'
    };

    let requestUrl = `${req.context.config.api.directory}/admin/organizations/${req.params.org_id}/tasks/`;

    if (options)
        requestUrl += '?' + querystring.stringify(options);

    return log(fetch)(requestUrl, { method: 'get', headers: req.context.headers })
        .then(response => response.json())
        .then(data => preprocessTasks(req, Object.assign({ STATES }, data || {})))
        /*.then(data => {
            return getTaskNames(req, res).then(NAMES => {
                return preprocessTasks(req, Object.assign({ STATES, NAMES }, data || {}));
            });
        })*/
        .catch(error => []);
}

function getTaskNames(req, res) {
    let requestUrl = `${req.context.config.api.directory}/admin/tasks/names/`;
    return log(fetch)(requestUrl, { method: 'get', headers: req.context.headers })
        .then(response => response.json())
        .catch(error => []);
}

function preprocessTasks(req, data) {
    if (!data) return data;

    let noQueryStates = data.STATES.filter(state => Boolean(req.query[state])).length === 0;

    data.STATES = data.STATES.map(state => {
        let value = noQueryStates ?
            (DEFAULT_STATES.indexOf(state) === -1 ? 0 : 1) :
            (req.query[state] ? 1 : 0);
        return { key: state, value };
    });

    return data;
}

module.exports = getTasks;
