﻿"use strict";

// dashboard controller
app.controller("dashboardController", ["$rootScope",
    "$scope",
    "$location",
    "$routeParams",
    "authService",
    "categoryDataService",
    "categorySubmissionDataService",
    "votingDataService",
    "judgeRulesService",
    "configDataService",
    "$q",
    function ($rootScope,
        $scope,
        $location,
        $routeParams,
        authService,
        categoryDataService,
        categorySubmissionDataService,
        votingDataService,
        judgeRulesService,
        configDataService,
        $q) {

        $scope.judgeRulesService = judgeRulesService;

        $scope.username = "";
        $scope.fullname = "";
        $scope.emailAddress = "";
        $scope.categories = [];
        $scope.categoriesGroupedByBallot = {};
        $scope.ballots = [];
        $scope.currentBallot = {};
        $scope.isFirstBallot = true;
        $scope.currentBallotId = parseInt($routeParams.ballotId);
        $scope.submittedBallotIds = [];
        $scope.pendingCategories = [];
        $scope.allCatgoriesSubmitted = false;
        $scope.completeCategories = [];
        $scope.votes = [];
        $scope.mostRecentVotes = [];
        $scope.randomNumber = Math.random();
        $scope.percentVotingComplete = 0;
        $scope.finishedLoading = false;
        $scope.getVoteTypeConfiguration = _getVoteTypeConfiguration;
        $scope.onBallotChanged = _onBallotChanged;
        $scope.submitDisabled = _submitDisabled;

        $scope.$on("submitVote", function (event, data) {
            _getCategories();
        });


        // ----- Helpers
        $scope.init = function () {

            $q.all([judgeRulesService.appConfig()])
                .then(function (rootScope) {
                    if (rootScope.length > 0 && rootScope[0].data.forceMemberManagerPage) {
                        $rootScope.forceMemberManagerPage = true;
                        $location.path('/manageMembers');
                        return;
                    }

                    // MemberTypeIDs: 1 (Individual); 2 (Company); 3 (Unknown); 4 (Judge)
                    if (rootScope.length > 0 && rootScope[0].data.membershipTypeID === 4) {
                        $rootScope.forceProfilePage = false;
                    }
                    else if (rootScope.length > 0 && rootScope[0].data.forceProfilePage) {
                        $rootScope.forceProfilePage = true;
                        $location.path('/profile');
                    }
                });

            var gettingCategories = _getCategories();
            var gettingUserInfo = _getUserInfo();

            $rootScope.isDetailsView = false;
            $q.all([gettingUserInfo, gettingCategories])
                .then(function () {
                    _getVotes().finally(function () {
                        $scope.finishedLoading = true;
                        $scope.showNoSubmissionsMsg = $scope.categories.length == 0;
                        $scope.submitDisabled();
                    });
                });
        };
        $scope.isActive = function (catId) {
            // No active categories on dashboard yet
            return false;
        };

        var _getUserInfo = function () {
            var deferred = $q.defer();

            authService.getUserInfo().then(function (results) {
                $scope.username = results.data.username;
                $scope.fullname = results.data.fullname;
                $scope.emailAddress = results.data.emailAddress;
                deferred.resolve();
            },
                function (error) {
                    console.error('error on getUserInfo');
                    deferred.reject();
                });

            return deferred.promise;
        };
        var _getCategories = function () {
            var deferred = $q.defer();

            categoryDataService.getCategories().then(function (results) {
                if (results.data.length > 0) {
                    for (var i = 0, iCount = results.data.length; i < iCount; i++) {
                        results.data[i].categoryName = judgeRulesService.getCategoryName(results.data[i]);
                    }

                    $scope.categories = results.data;

                    $scope.roundIds = [];
                    $scope.pendingCategories = [];
                    $scope.completeCategories = [];

                    $scope.categoriesGroupedByBallot =
                        results.data.reduce(function (result, current) {
                            result[current.ballotId] = result[current.ballotId] || [];
                            result[current.ballotId].push(current);
                            return result;
                        }, {});


                    $.each($scope.categories, function (index, category) {
                        if ($scope.roundIds.indexOf(category.roundId) < 0) {
                            $scope.roundIds.push(category.roundId);
                        }

                        //$scope.pendingCategories.push(category);

                    });

                    $.each($scope.categoriesGroupedByBallot, function (index, ballotCategories) {
                        if (ballotCategories.length > 0) {

                            var isSubmitted = ballotCategories.filter(function (e) { return e.submitted; }).length > 0;
                            var isComplete = ballotCategories.filter(function (e) { return e.percentCompleted < 100; }).length === 0;
                            var allowPartiallyCompleted = ballotCategories[0].allowPartiallyCompleted === 1;

                            $scope.ballots.push({
                                ballotId: ballotCategories[0].ballotId,
                                ballotName: ballotCategories[0].ballotName,
                                isComplete: isComplete,
                                allowPartiallyCompleted: allowPartiallyCompleted,
                                isSubmitted: isSubmitted
                            });

                            if (ballotCategories[0].ballotId === $scope.currentBallotId) {
                                $.each(ballotCategories, function (index, category) {
                                    $scope.pendingCategories.push(category);
                                });
                            }
                        }
                    });

                    var filteredBallots = $scope.ballots.filter(function (e) { return e.ballotId === $scope.currentBallotId; });
                    if (filteredBallots.length > 0) {
                        $scope.currentBallot = filteredBallots[0];
                    }

                    $scope.percentVotingComplete = (+($scope.completeCategories.length / $scope.categories.length * 100).toFixed(2));

                    deferred.resolve();
                }
            },
                function (error) {
                    console.error('error on getCategories');
                    deferred.reject();
                });

            return deferred.promise;
        };
        function _getVoteTypeConfiguration(voteTypeConfigurationDetails, submissionCount) {
            if ('orderedList' in voteTypeConfigurationDetails) {
                return voteTypeConfigurationDetails.orderedList.voteCount;
            }
            else if ('orderedListWithWriteIns' in voteTypeConfigurationDetails) {
                return voteTypeConfigurationDetails.orderedListWithWriteIns.voteCount;
            }
            else if ('unorderedList' in voteTypeConfigurationDetails) {
                return voteTypeConfigurationDetails.unorderedList.voteCount;
            }
            else if ('unorderedListWithWriteIns' in voteTypeConfigurationDetails) {
                return voteTypeConfigurationDetails.unorderedListWithWriteIns.voteCount;
            }
            else { // criteria voting category
                return submissionCount;
            }

        }
        var _getVotes = function () {
            var deferred = $q.defer();

            votingDataService.getVotesForContact().then(function (results) {
                if (results !== void 0) {
                    $scope.votes = results.data;

                    for (var i = 0, voteCount = $scope.votes.length; i < voteCount; i++) {
                        for (var j = 0, categoryCount = $scope.categories.length; j < categoryCount; j++) {
                            if ($scope.categories[j].id === $scope.votes[i].categoryId) {
                                $scope.votes[i].category = $scope.categories[j];
                                break;
                            }
                        }
                    }
                }

                deferred.resolve();
            },
                function (error) {
                    console.error('error on getVotesForContact');
                    deferred.reject();
                });

            return deferred.promise;
        };

        function _onBallotChanged(ballot) {
            console.log('ballotId:' + ballot.ballotId);

            $scope.pendingCategories =
                $scope.categories.filter(function (e) {
                    return e.ballotId == ballot.ballotId;
                });

            $scope.currentBallot = ballot;
            $scope.currentBallotId = ballot.ballotId;

            // set disabled on submit button if submitted
            $scope.submitDisabled();
        }

        $scope.$on('submitted-ballots', function (e, ballotId) {
            var index = $scope.ballots.map(function (e) { return e.ballotId; }).indexOf($scope.currentBallotId);
            $scope.ballots[index].isSubmitted = 1;

            $location.path('/ballotDashboard');
        });

        function _submitDisabled(disable) {
            if ($scope.finishedLoading) {
                /*
                  isComplete: isComplete,
                  allowPartiallyCompleted: allowPartiallyCompleted,
                 */
                var index = $scope.ballots.map(function (e) { return e.ballotId; }).indexOf($scope.currentBallotId);
                if (index > -1) {
                    var ballot = $scope.ballots[index];
                    return ballot.isSubmitted || (!ballot.isComplete && !ballot.allowPartiallyCompleted);
                }
            }
        }

        $scope.init();
    }]);