﻿(function () {
    'use-strict';

    angular.module('judgeapp').directive('ygDatePicker', ['$rootScope', datePicker]);

    function datePicker($rootScope) {
        return {
            restrict: 'E',
            require: 'ngModel',
            scope: {
                date: '='
            },
            templateUrl: $rootScope.localizeUrl('/spa-app/views/fragments/html/ygDatePicker'),
            link: _link
        };

        function _link(scope, element, attributes, ngModel) {

            scope.$watch('date', function () {                
                scope.result = scope.date instanceof Date?
                {
                    year: scope.date.getFullYear(),
                    month: scope.date.getMonth(),
                    day: scope.date.getDate()
                    } : {
                    year: '',
                    month: '',
                    day: ''
                };
            });

            scope.isValid = true;

            scope.years = [];
            scope.days = [];
            scope.setDate = function () {
                var parsed = moment([scope.result.year, scope.result.month, scope.result.day]);

                if (parsed.isValid()) {
                    ngModel.$setValidity('ygDatePicker', true);
                    scope.isValid = true;
                }
                else {
                    ngModel.$setValidity('ygDatePicker', false);
                    scope.isValid = false;
                    return;
                }

                scope.date = new Date(scope.result.year, scope.result.month, scope.result.day);
            };

            _init();

            function _init() {
                var currentYear = new Date().getFullYear();
                for (var i = 0; i <= 112; i++) {
                    scope.years.push(currentYear - i);
                }

                for (var i = 1; i <= 31; i++) {
                    scope.days.push(i);
                }
            }
        }
    }

})();