var _ = require('lodash');
var random = require('../common/random');

var common = {
    is, is_not, more, less, and, or, ternary, empty,
    dash_empty, fallback,
    join, unique, contains,
    on_off, link_url, random_string
};

module.exports = Object.assign(
    common,
    require('./i18n'),
    require('./date'),
    require('./number'),
    require('./string_manipulation'),
    require('./contacts'),
    require('./org_object'),
    require('./org_service'),
    require('./domain'),
    require('./data_record'),
    require('./notification'),
    require('./utm')
);

function is(a, b, options) {
    if (options.fn === undefined && options.inverse === undefined)
        return a === b;
    return a === b ? options.fn(this) : options.inverse(this);
}

function is_not(a, b, options) {
    if (options.fn === undefined && options.inverse === undefined)
        return a !== b;
    return a !== b ? options.fn(this) : options.inverse(this);
}

function more(a, b) {
    return a > b;
}

function less(a, b) {
    return a < b;
}

function and(...args) {
    let output = Boolean(args[0]);
    for (let i = 1; i < args.length - 1 && output; i++)
        output = Boolean(output && args[i]);
    return output;
}

function or(...args) {
    let output = Boolean(args[0]);
    for (let i = 1; i < args.length - 1 && !output; i++)
        output = Boolean(output || args[i]);
    return output;
}

function ternary(x, a, b) {
    return x ? a : b;
}

function empty(x) {
    if (x === null || x === undefined)
        return true;

    switch (typeof x) {
        case 'string': return x === '';
        case 'object': return x instanceof Array ? !x.length : !Object.keys(x).length;
        case 'number': return Number.isNaN(x);
    }
}

function dash_empty(x) {
    return x === null || x === undefined || x === '' ? '—' : x;
}

function fallback(...args) {
    for (let i = 0; i < args.length - 2; i++) {
        if (args[i] !== null && args[i] !== undefined && args[i] !== '')
            return args[i];
    }
    return args[args.length - 2];
}

function join(...args) {
    if (args[1] instanceof Array)
        return args[1].filter(Boolean).join(args[0]);
    return args.slice(1, -1).filter(Boolean).join(args[0]);
}

function unique(...args) {
    return _.uniq(args.slice(0, -1));
}

function contains(list, x) {
    return list instanceof Array && list.indexOf(x) !== -1;
}

function on_off(x) {
    return x === undefined || x === null ? '—' : (x ? '\u2713' : '\u2718');
}

function link_url(url) {
    return !url || /^https?:\/\//.test(url) ? url : 'http://' + url;
}

function random_string(length) {
    return random.getString(length);
}
