/* eslint camelcase: "off" */
/* eslint promise/no-nesting: "off" */

import {get_string} from 'core/str';
import {getString} from 'core/str';
import {call} from 'core/ajax';
import {render} from 'core/templates';

/* Determine the proper getstrings function to use (MDL4.3+ recommends use of getStrings, which is jquery independent) */
const getStrFunc = (getString !== undefined) ? getString : get_string;

/**
 * Process the results for auto complete elements.
 *
 * @param {String} selector The selector of the auto complete element.
 * @param {Array} results An array or results.
 * @return {Array} New array of results.
 */
export function processResults(selector, results) {
    const users = [];
    if (Array.isArray(results)) {
        results.forEach((user) => {
            users.push({
                value: user.id,
                label: user._label
            });
        });
        return users;
    } else {
        return results;
    }
}

/**
 * Source of data for Ajax element.
 *
 * @param {String} selector The selector of the auto complete element.
 * @param {String} query The query string.
 * @param {Function} success A callback function receiving an array of results.
 * @param {Function} failure A callback function to be called in case of failure, receiving the error message.
 */
export function transport(selector, query, success, failure) {
    const element = document.querySelector(selector);
    const userfields = element.getAttribute('userfields').split(',');

    let perpage = parseInt(element.getAttribute('perpage'));
    if (isNaN(perpage)) {
        perpage = 100;
    }

    call([{
        methodname: 'local_treestudyplan_find_users',
        args: {
            search: query,
            searchanywhere: true,
            page: 0,
            perpage: perpage + 1
        }
    }])[0].then(function(results) {
        if (results.length <= perpage) {
            // Render the label.
            const profileRegex = /^profile_field_(.*)$/;
            const promises = [];
            results.forEach((user) => {
                let ctx = user;
                const identity = [];
                userfields.forEach((k) => {
                    const result = profileRegex.exec(k);
                    if (result) {
                        if (user.customfields) {
                            user.customfields.forEach(function(customfield) {
                                if (customfield.shortname === result[1]) {
                                    ctx.hasidentity = true;
                                    identity.push(customfield.value);
                                }

                            });
                        }
                    } else {
                        if (typeof user[k] !== 'undefined' && user[k] !== '') {
                            ctx.hasidentity = true;
                            identity.push(user[k]);
                        }
                    }
                });
                ctx.identity = identity.join(', ');
                promises.push(render('local_treestudyplan/form/form-user-selector-suggestion', ctx));
            });

            return Promise.all(promises).then((args) => {
                let i = 0;
                results.forEach((user) => {
                    user._label = args[i];
                    i++;
                });
                success(results);
                return;
            });
        } else {
            return getStrFunc('toomanyuserstoshow', 'core', '>' + perpage).then(function(toomanyuserstoshow) {
                success(toomanyuserstoshow);
                return;
            });
        }

    }).fail(failure);
}
