const _ = require('lodash');
const i18n = require('../common/i18n');
const preprocessPagedList = require('../preprocessPagedList');
const preprocessItem = require('./preprocess');

function getFilter(req, data) {
    if (req.params.plan === 'paid')
        return 'paid';
    else if (req.query.query)
        return 'search';
    else if (data.result)
        return 'all';
}

function preprocessList(req, res, data) {
    if (!data) return {};

    data.result = (data.result || []).map(item => preprocessItem(req, item));
    data.query = req.query.query;

    addCutLine(req, data);

    return Object.assign(preprocessPagedList(req, data), {
        sort_orders: req.context.sort_orders,
        filter: getFilter(req, data)
    });
}

function addCutLine(req, data) {
    let stats = data.stats;

    if (data.multishard && data.pages > 1) {
        let dictionary = i18n.getDictionary(req.context);
        if (stats && stats.organizations_total_count && !req.params.plan) {
            data.cut_line = dictionary.pick('org_list.cut_line.more.content', {
                n_organizations: dictionary.pluralize(
                    stats.organizations_total_count - data.per_page,
                    dictionary.pick('org_list.cut_line.more.organizations'),
                    _.get(dictionary.storage, 'org_list.cut_line.more.pattern')
                )
            });
        }
        else if (req.query.query) {
            data.cut_line = dictionary.pick('org_list.cut_line.unspecified.content', {
                n_organizations: dictionary.pluralize(
                    data.result ? data.result.length : data.per_page,
                    dictionary.pick('org_list.cut_line.unspecified.more_organizations')
                )
            });
        }
    }

    return data;
}

module.exports = preprocessList;
