var extend = require('extend');

function getError(field, errors, config) {
    if (errors[field]) {
        return errors[field];
    }

    if (!config.fields) {
        return null;
    }

    if (!config.fields[field]) {
        var split = field.split('/');

        if (split.length > 1) {
            return getError(split[split.length - 1], errors, config);
        }

        return null;
    }

    return config.fields[field].error;
}

function getProp(field, key, config) {
    if (!config.fields) {
        return null;
    }

    if (!config.fields[field]) {
        var split = field.split('/');

        if (split.length > 1) {
            return getProp(split[split.length - 1], key, config);
        }

        return null;
    }

    return config.fields[field][key];
}

function getConfig(field, errors, config, overwrite) {
    return extend(true, {
        label: getProp(field, 'label', config),
        help: getProp(field, 'help', config),
        attrs: {
            placeholder: getProp(field, 'placeholder', config)
        },
        hasError: !!errors[field],
        error: getError(field, errors, config),
        nullOption: {value: '', text: getProp(field, 'nullOption', config)}
    }, overwrite);
}

function flattenStruct(ob) {
    var toReturn = {};

    for (var i in ob) {
        if (typeof ob[i] === 'object') {
            var flatObject = flattenStruct(ob[i]);

            for (var x in flatObject) {
                toReturn[x] = flatObject[x];
            }
        } else {
            toReturn[i] = ob[i];
        }
    }

    return toReturn;
}

function extractErrors(json) {
    var errors = {};

    if (json.message) {
        errors.message = json.message;
    }

    if (!json.errors) {
        return errors;
    }

    errors.fields = {};

    json.errors.forEach(function(error) {
        if (!error.path || !error.message) {
            return;
        }

        var field = error.path.substr(1);

        errors.fields[field] = error.message;
    });

    return errors;
}

module.exports = {
    merge: extend,
    getError: getError,
    getProp: getProp,
    getConfig: getConfig,
    flattenStruct: flattenStruct,
    extractErrors: extractErrors
};
