﻿(function () {
    'use-strict';

    angular.module('judgeapp').directive('creditCardExpiry', ['$rootScope', creditCardExpiry]);

    function creditCardExpiry($rootScope) {
        return {
            require: '^form',
            restrict: 'E',
            scope: {
                month: '=',
                year: '=',
                required: '='
            },
            templateUrl: $rootScope.localizeUrl('/spa-app/views/fragments/html/creditCardExpiry'),
            link: function (scope, element, attrs, ngForm) {
                function validateCreditCardExpiry() {
                    const testYear = parseInt(scope.year);
                    const testMonth = parseInt(scope.month);
                    const currDate = new Date();

                    if (!scope.required || isNaN(testYear) || isNaN(testMonth))
                        return true;

                    return testYear > currDate.getFullYear() ||
                        testYear === currDate.getFullYear() && testMonth >= currDate.getMonth() + 1;
                }

                scope.form = ngForm;
                scope.currentDate = new Date();

                scope.$watch(validateCreditCardExpiry, function (newValue) {
                    ngForm.$setValidity("creditCardExpiry", newValue);
                });
            }
        };
    }
})();