﻿"use strict";

// ballot dashboard controller
app.controller("ballotDashboardController", ["$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 = 0;
        $scope.submittedBallotIds = [];
        $scope.pendingCategories = [];
        $scope.allCatgoriesSubmitted = false;
        $scope.completeCategories = [];
        $scope.randomNumber = Math.random();
        $scope.finishedLoading = false;

        // ----- Helpers
        $scope.init = function () {

            $q.all([judgeRulesService.appConfig()])
                .then(function (rootScope) {
                    // MemberTypeIDs: 1 (Individual); 2 (Company); 3 (Unknown); 4 (Judge)
                    if (rootScope.length > 0 && rootScope[0].data.forceMemberManagerPage) {
                        $rootScope.forceMemberManagerPage = true;
                        $location.path('/manageMembers');
                        return;
                    }

                    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 () {
                            $scope.finishedLoading = true;
                            if ($scope.ballots.length === 1 && $scope.ballots[0].isSubmitted === 0) {
                                $location.path('/dashboard/' + $scope.ballots[0].ballotId);
                            }

                        });
                });
        };
        $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);
                        }

                    });

                    $.each($scope.categoriesGroupedByBallot, function (index, ballotCategories) {
                        if (ballotCategories.length > 0) {

                            var isSubmitted = ballotCategories.filter(function (e) { return e.submitted === 1; }).length > 0;
                            $scope.ballots.push({ ballotId: ballotCategories[0].ballotId, ballotName: ballotCategories[0].ballotName, isSubmitted: isSubmitted });

                        }
                    });

                    deferred.resolve();
                }
            },
                function (error) {
                    console.error('error on getCategories');
                    deferred.reject();
                });

            return deferred.promise;
        };
        

        $scope.init();
    }]);