/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
/*jshint maxparams: 13 */
angular.module('election-event-manage', [])
    .controller('election-event-manage', function($scope, $rootScope, sessionService,
        endpoints, $templateCache, $http, $state, $mdDialog, $q, gettextCatalog, settler, boardActivation, $mdToast, toastCustom, entitiesCounterService) {
        'use strict';

        // set state to be used in the HTML template
        $scope.state = $state.current.name;
        $rootScope.$on('$stateChangeSuccess', function(event, toState) {
            $scope.state = toState.name;
        });

        /*
        Launch the endpoint responsible of syncronizing the application status
        */
        $scope.synchronizeInTabs = function() {
            sessionService.startSync();
            $scope.errors = {};

            var URLsToSyncronize = [endpoints.host + endpoints.preconfiguration,
                (endpoints.host + endpoints.synchronizeVoterPortalEEID).replace(
                    '{electionEventId}', sessionService.getSelectedElectionEvent().id),
                (endpoints.host + endpoints.updateComputationStatus).replace(
                    '{electionEventId}', sessionService.getSelectedElectionEvent().id),
                (endpoints.host + endpoints.updateBallotBoxStatus).replace(
                    '{electionEventId}', sessionService.getSelectedElectionEvent().id)
            ];

            try {
                $q.allSettled(URLsToSyncronize.map(function(URL) {
                    return $http.post(URL);
                })).then(
                    function(responses) {
                        sessionService.stopSync();
                        var settled = settler.settle(responses);
                        if (settled.ok) {
                            entitiesCounterService.getTheMainItemsCount();
                            entitiesCounterService.getEEItemsStuff(sessionService.getSelectedElectionEvent());
                            switch ($state.current.name) {
                                case 'ballots':
                                    $rootScope.$broadcast('refresh-ballots');
                                    break;
                                case 'voting-cards':
                                    $rootScope.$broadcast('refresh-voting-card-sets');
                                    break;
                                case 'electoral-authorities':
                                    $rootScope.$broadcast('refresh-authorities');
                                    break;
                                case 'ballot-boxes':
                                    $rootScope.$broadcast('refresh-ballot-boxes');
                                    break;
                                default:
                                    break;
                                }
                        } else {
                            $scope.errors.synchronizeFailed = true;
                            $mdDialog.show(
                                $mdDialog.customAlert({
                                    locals: {
                                        title: gettextCatalog.getString('Synchronize'),
                                        content: gettextCatalog.getString('Synchronization failed due to connectivity errors')
                                    }
                                })
                            );
                        }
                    }
                );
            } catch (e) {
                sessionService.stopSync();
                $scope.data.message = e;
            }
        };

        function DialogController($scope, $mdDialog) {
            $scope.hide = function() {
                $mdDialog.hide();
            };
            $scope.cancel = function() {
                $mdDialog.cancel();
            };
            $scope.answer = function(answer) {
                $mdDialog.hide(answer);
            };
        }

        /*
         Launch the endpoint responsible of activating the administration board status
         */
        $scope.activateAdminBoard = function() {
            boardActivation.init('adminBoard');
            boardActivation.adminBoardActivate()
                .then( 
                    function(response){ 
                        if(response && response.data && response.data.error != ''){
                            $mdToast.show(
                                toastCustom.topCenter(gettextCatalog.getString('The Administration Board could not be activated'), 'error')
                            );
                        }else{
                            boardActivation.openBoardAdmin();
                        }
                    }
                );
        };


        /*
         Remove admin board key from memory
         */
        $scope.deactivateAdminBoard = function() {

            var adminBoard = sessionService.getSelectedAdminBoard();
            if (adminBoard) {
                adminBoard.privateKey = undefined;
                sessionService.setSelectedAdminBoard(adminBoard);
            }
        };

        $scope.isAdminAuthorityActivated = function() {
            var adminBoard = sessionService.getSelectedAdminBoard();
            if (!adminBoard) {
                return false;
            }
            return sessionService.getSelectedAdminBoard().privateKey;
        };
    });
