﻿(function () {
    'use strict';
    angular.module('judgeapp').directive('submitVotesForRound', submitVotesForRound);
    submitVotesForRound.$inject = ['votingService', 'authService', '$rootScope'];

    function submitVotesForRound(votingService, authService, $rootScope) {
        return {
            restrict: 'A', // Make your own custom button.
            scope: {
                submitVotesForRound: '=', // {number|number[]} - Round Id(s)
                onSubmitted: '&?'
            },
            link: link
        };

        function link(scope, element, attributes) {
            element[0].addEventListener('click', onClick);

            function onClick() {
                $.awards.confirm({
                    title: "Submit",
                    message: 'Are you sure that you have completed your voting and would like to submit?',
                    largeSize: false,
                    okFunction: function () {
                        var isArray = Object.prototype.toString.call(scope.submitVotesForRound) === '[object Array]';
                        var roundIds = scope.submitVotesForRound;
                        if (!isArray) {
                            roundIds = [scope.submitVotesForRound];
                        }
                        votingService.submitVotesByRoundIds(roundIds).then(function () {
                            if (scope.onSubmitted) {
                                scope.onSubmitted();
                            }

                            if ($rootScope.blockSiteAccessAfterSubmittingVotes === true) {
                                authService.logOut();
                            }
                        });
                    },
                    okText: "Okay"
                });
            }
        }
    }
})();