(function () {
    'use strict';

    angular
        .module('setoresApp')
        .directive('datePicker', datePicker);


    datePicker.$inject = [];

    /* @ngInject */
    function datePicker() {
        return {
            restrict: 'A',
            require: 'ngModel',
            scope: false,
            link: linkFunc
        };

        function linkFunc(scope, element, attrs, ngModel) {
            let icons = element.find('i');

            element.datepicker({
                nextText: '',
                prevText: '',
                minDate: attrs.minDate,
                maxDate: attrs.maxDate,
                showOn: 'both',
                dateFormat: "yy-mm-dd",
                buttonText: '',
                onClose: function (date) {
                    ngModel.$setViewValue(date);
                    ngModel.$setTouched();

                    if (element.datepicker('getDate') === null) {
                        ngModel.$modelValue = date;
                    } else {
                        ngModel.$modelValue = element.datepicker('getDate');
                    }

                    ngModel.$viewChangeListeners.forEach(func => func());

                    scope.$apply();
                }
            });

            ngModel.$parsers.push(function (value) {
                if (value && Object.prototype.toString.call(value) === "[object Date]") {

                    if (isNaN(value.getTime())) {

                        ngModel.$setValidity('valid', false);
                        ngModel.errorDescription = 'Informe uma data válida';

                        return ngModel.$viewValue;
                    } else {
                        ngModel.$setValidity('valid', true);
                        ngModel.errorDescription = null;

                        return value;
                    }
                } else {
                    ngModel.$setValidity('valid', true);
                    ngModel.errorDescription = null;
                    return value;
                }
            });
        }
    }
})();
