'use strict';

/*
    How to use: http://plnkr.co/edit/HnF90JOYaz47r8zaH5JY?p=preview
*/
angular.module('qusion.ui.validate', [
])
    .directive('qnValidate', [
        function() {
            return {
                //require: 'ngModel',
                link: function(scope, element, attr) {
                    var form = element.inheritedData('$formController');
                    // no need to validate if form doesn't exists
                    if (!form) return;
                    // validation model
                    var validate = attr.qnValidate;
                    // watch validate changes to display validation
                    scope.$watch(validate, function(errors) {

                        // every server validation should reset others
                        form.$serverError = { };


                        // if errors is undefined or null just set invalid to folse and return
                        if (!errors) {
                            form.$serverInvalid = false;
                            return;
                        }
                        // set $serverInvalid to true|false
                        form.$serverInvalid = (errors.length > 0);

                        // loop through errors
                        angular.forEach(errors, function(error, i) {
                            form.$serverError[error.key] = { $invalid: true, message: error.value };
                        });
                    });
                }
            };
        }
    ]);