import VeeValidate from 'vee-validate';

Vue.use(VeeValidate);

Vue.prototype.$setErrorsFromResponse = function (error_response) {
    // only allow this function to be run if the validator exists
    if (!this.hasOwnProperty('$validator')) {
        return;
    }

    // clear errors
    this.$validator.errors.clear();
    this.$children
        .forEach(child_component => {
            child_component.$validator.errors.clear();
        });

    // check if errors exist
    if (!error_response.hasOwnProperty('errors')) {
        return;
    }

    // insert errors from response
    Object.keys(error_response.errors).map(key => {
        let error_string = error_response.errors[key].join(', '),
            vm_field = this.$validator
                .fields
                .find({
                    name: key
                });

        if (!vm_field) {
            // If not found in current component, look if the field is found in child components
            const child = this.$children
                .filter((child_component) => {
                    return child_component.$validator
                        .fields
                        .find({
                            name: key
                        });
                })[0];

            if (child) {
                vm_field = child.$validator
                    .fields
                    .find({
                        name: key
                    });
            }
        }

        this.$validator.errors.add({
            vmId: vm_field.vmId,
            field: key,
            msg: error_string
        });
    });

};
