import _ from 'lodash';

let DEBUG_ENABLED = /[\?&]debug=[^&]+/i.test(location.search);

// @if NODE_ENV='development'
DEBUG_ENABLED = true;
// @endif

function buildUrl(url, options) {
    const params = [];

    _.each(options, (value, key) => {
        params.push(
            `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
        );
    });

    return url + (params.length ? `?${params.join('&')}` : '');
}

/**
 * Отправляет логи на сервер
 * @param {Object} options
 */
function sendServiceLog(options) {
    const appRoot = _.get(window.ya, 'connect.config.app.root');
    let prefix = _.get(window.ya, 'connect.config.api.app.service', '/');

    if (prefix.indexOf(appRoot) !== 0) {
        prefix = appRoot + prefix.substring(1);
    }

    (new Image()).src = buildUrl(`${prefix}/log`, options);
}

/**
 * Логирование ошибок
 * @param {String} message
 * @param {Object} options  дополнительные данные
 */
function error(message, options) {
    if (DEBUG_ENABLED && window.console) {
        console.log.apply(console, arguments); // eslint-disable-line no-console
    }

    const basicOptions = {
        url: location.href,
        uid: _.get(window.ya, 'connect.initial.state.session'),
        tag: 'js-error',
    };

    const reportOptions = {
        message,
        options: JSON.stringify(_.extend(basicOptions, options)),
        ua: navigator.userAgent,
    };

    const debugId = (location.search.match(/(\?|&)debug=([^&]+)/) || [])[2];

    if (debugId) {
        reportOptions.debug = debugId;
    }

    sendServiceLog(reportOptions);
}

/**
 * Запись в лог
 */
function info() {
    if (DEBUG_ENABLED && window.console) {
        console.log.apply(console, arguments); // eslint-disable-line no-console
    }
}

export default {
    info,
    error,
    sendServiceLog,
};
