﻿(function () {
    'use strict';
    angular.module('judgeapp').directive('submitVotesForBallot', submitVotesForBallot);
    submitVotesForBallot.$inject = ['votingService', 'authService', '$rootScope'];

    function submitVotesForBallot(votingService, authService, $rootScope) {
        return {
            restrict: 'A', // Make your own custom button.
            scope: {
                submitVotesForBallot: '=', // {number|number[]} - Ballot 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 for the "{0}" Ballot and would like to submit?'.format(scope.submitVotesForBallot.ballotName),
                    largeSize: false,
                    okFunction: function () {
                        var isArray = Object.prototype.toString.call(scope.submitVotesForBallot) === '[object Array]';
                        var ballotIds = scope.submitVotesForBallot.ballotId;
                        if (!isArray) {
                            ballotIds = [scope.submitVotesForBallot.ballotId];
                        }
                        votingService.submitVotesByBallotId(ballotIds).then(function () {
                            if (scope.onSubmitted) {
                                scope.onSubmitted();

                                //remove ballot from dropdown and if last ballot hide the "submit my ballot" button"
                                scope.$emit('submitted-ballots', scope.submitVotesForBallot);

                            }

                            //if ($rootScope.blockSiteAccessAfterSubmittingVotes === true) {
                            //    authService.logOut();
                            //}
                        });
                    },
                    okText: "Okay"
                });
            }
        }
    }
})();