import _ from 'lodash';
import { i18n } from 'lib/i18n';
import DepartmentStore from 'stores/Departments';
import getErrorMap from './getErrorMap';

function xi18n(key, options) {
    return i18n(`department_validation.${key}`, options);
}

function toArray(x) {
    if (!x) {
        return [];
    }

    return x.toArray ? x.toArray() : [x];
}

const departmentValidator = {

    getNameError(data, locale = 'ru') {
        const minLength = 2;
        const maxLength = 40;

        let name = _.get(data, `name.${locale}`);

        if (name === undefined) {
            return null;
        }

        name = _.trim(name);

        if (!name || name.length < minLength || name.length > maxLength) {
            return xi18n('name_length_out_of_bounds', { minLength, maxLength });
        }

        return null;
    },

    getDescriptionError(data, locale = 'ru') {
        const maxLength = 100;

        const description = _.get(data, `description.${locale}`);

        if (description === undefined) {
            return null;
        }

        if (description.length > maxLength) {
            return xi18n('description_too_long', { maxLength });
        }

        return null;
    },

    getMembersError(data) {
        const department = DepartmentStore.get(data.department_id);

        if (data.members && department) {
            const allParents = toArray(department.get('parents'));
            const parentMembers = data.members.filter(item =>
                item.type === 'department' && allParents.indexOf(String(item.id)) !== -1);

            if (parentMembers.length) {
                return i18n('backend_errors.constraint_validation.cant_move_department_to_descendant');
            }
        }
    },

};

departmentValidator.getErrors = getErrorMap(departmentValidator);

export default departmentValidator;
