﻿(function () {
    'use strict';
    SinglePageVotingController.$inject = [
        'judgeRulesService',
        'votingDataService',
        'categoryDataService',
        '$q'
    ];
    angular.module('judgeapp').controller('SinglePageVotingController', SinglePageVotingController);

    /**
     * NOTE: THE SINGLE PAGE VOTING FEATURE IS UNFINISHED AND ABANDONED. WE'VE DECIDED NOT TO PURSUE THIS NOW AND INSTEAD MAY FINISH IT IN THE FUTURE.
     */
    function SinglePageVotingController
        (
            judgeRulesService,
            votingDataService,
            categoryDataService,
            $q
        ) {
        var _vm = this;

        _vm.votes = [];
        _vm.categories = [];
        _vm.hasLoadedData = false;
        _vm.votesByCategoryId = {};
        _vm.voteTypeConfig = {};
        _vm.getVoteTypeConfig = _getVoteTypeConfig;
        _vm.saveVote = _saveVote;
        _vm.deleteVote = _deleteVote;
        _vm.roundIds = [];
        _vm.canSubmitVotes = false;
        _vm.onVotesSubmitted = _onVotesSubmitted;
        /**
         * Property = vote id
         */
        _vm.voteIdsBeingLoaded = {};

        _activate();

        function _saveVote(vote) {
            _vm.voteIdsBeingLoaded[vote.voteId] = true;

            votingDataService.setWriteInVote(vote.details.writeIn)
                .then(function () {
                    // This is lame, we should have a restful endpoint that returns our newly created vote.
                    // Instead we have to reload the votes to get the new id. Plus other votes get cleared.
                    _loadVotes().then(_setupData);
                })
                .catch(function () {
                    $.awards.notify.error("Error")
                })
                .finally(function () {
                    delete _vm.voteIdsBeingLoaded[vote.voteId];
                });
        }

        function _deleteVote(vote) {
            _vm.voteIdsBeingLoaded[vote.voteId] = true;

            votingDataService.deleteVote(vote.voteId)
                .then(function () {
                    vote.voteId = null;
                })
                .catch(function () {
                    $.awards.notify.error("Error")
                })
                .finally(function () {
                    delete _vm.voteIdsBeingLoaded[vote.voteId];
                });
        }

        function _setupData() {
            _vm.votesByCategoryId = {};

            var canSubmitVotes = true;

            for (var i = 0; i < _vm.votes.length; i++) {
                var vote = _vm.votes[i];

                if (vote.categoryId in _vm.votesByCategoryId) {
                    _vm.votesByCategoryId[vote.categoryId].push(vote);
                } else {
                    _vm.votesByCategoryId[vote.categoryId] = [vote];
                }
            }

            _vm.roundIds = [];
            for (var i = 0; i < _vm.categories.length; i++) {
                var category = _vm.categories[i];

                if (category.submitted && canSubmitVotes) { canSubmitVotes = false; }

                if (_vm.roundIds.indexOf(category.roundId) < 0) {
                    _vm.roundIds.push(category.roundId);
                }

                if (!(category.id in _vm.votesByCategoryId)) {
                    // Since there is an empty vote, they user cannot submit.

                    vote = {
                        details: {
                            writeIn: {
                                categoryId: category.id,
                                field1: ''
                            }
                        }
                    };

                    var config = _getVoteTypeConfig(category);
                    if (config.writeInField2Name) {
                        vote.details.writeIn.field2 = '';
                    }
                    if (config.writeInField3Name) {
                        vote.details.writeIn.field3 = '';
                    }

                    _vm.votesByCategoryId[category.id] = [vote];
                }
            }

            _vm.canSubmitVotes = canSubmitVotes;
        }

        function _getVoteTypeConfig(category) {
            return category.voteTypeConfigurationDetails.unorderedListWithWriteIns;
        }

        function _loadVotes() {
            return votingDataService.getVotesForContact()
                .then(function (response) {
                    _vm.votes = response.data
                });
        }

        function _onVotesSubmitted() {
            _vm.canSubmitVotes = false;
        }

        function _activate() {
            judgeRulesService.hideVideo();

            var votesPromise = _loadVotes();
            var categoryPromise = categoryDataService.getCategories()
                .then(function (response) {
                    _vm.categories = response.data;
                });

            $q.all([votesPromise, categoryPromise])
                .then(function () {
                    _setupData();
                    _vm.hasLoadedData = true;
                });
        }
    }
})();