/**
 * Created by Lidia Freitas on 04/02/2017.
 */
(function () {
    'use strict';

    angular
        .module('setoresApp')
        .factory('FormValidation', FormValidation);

    FormValidation.$inject = ['$timeout'];

    /* @ngInject */
    function FormValidation($timeout) {

        function FormValidation(form) {
            this.form = form;
        }

        FormValidation.prototype.setControlsValidation = function () {
            let self = this;
            let callbackFunctions = Array.prototype.slice.call(arguments);

            self.form.$$element.on('submit', validateInputs);

            if (self.form.$$controls) {
                self.form.$$controls.forEach(function (item) {
                    if (item.$name === '') return;

                    let addCustomListeners = true;
                    item.customValidation = true;

                    item.$viewChangeListeners.some(function (func) {
                        if (func.name === 'validateInputs' || func.name === 'checkEmpty') {
                            addCustomListeners = false;
                            return true;
                        }
                    });

                    if (addCustomListeners) {
                        item.$viewChangeListeners.push(validateInputs);
                        item.originalValue = item.$viewValue;
                    }
                });
            }

            function validateInputs(event) {
                self.eventTrigger = event;
                $timeout(function () {
                    if (!self.form.$$controls || self.form.$$controls.length === 0) return;
                    self.form.$$controls.forEach(function (item) {
                        let valid = false;

                        if (self.form.$submitted) {
                            valid = (item.$valid || (item.previousViewValue !== undefined && item.previousViewValue === item.$viewValue));
                        } else {
                            valid = !(item.$dirty && item.$invalid);
                        }

                        item.customValidation = valid;

                        if (self.form.$valid)
                            self.form.$valid = valid;
                    });

                    callbackFunctions.forEach(function (fun) {
                        fun(self)
                    });
                });
            }
        };

        FormValidation.prototype.resetControlsValidation = function () {
            let self = this;

            self.form.$$controls.forEach(function (item) {
                item.$parsers = [];
                item.$viewChangeListeners = [];
                item.$setViewValue();
                item.$$element.val(null);
                item.$setUntouched();
                item.$setPristine();
                item.customValidation = false;
                if (item.$validators.required) {
                    item.$setValidity('required', false);
                }

                item.$render();
            });

            self.form.$setPristine();

        };

        // TODO: Implementar validação de campos via servidor
        FormValidation.prototype.setFormErrors = function (errors) {
            let self = this;

            errors.forEach(function (error) {
                self.form.$$controls.some(function (item) {
                    if (item.$name === error.AttributeName) {
                        item.customValidation = true;
                        item.previousViewValue = item.$viewValue;
                        item.serverMessage = error.ErrorDescriptions.join();
                        return true;
                    }
                });
            });
        };

        return FormValidation;
    }

})();

