/*
 * 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
 */
angular.module('electoral-authorities', [])
    .controller('electoral-authorities', function($scope, $rootScope, $http, endpoints,
        sessionService, $mdDialog, $mdToast,
        $templateCache, CustomDialog, gettextCatalog, toastCustom, boardActivation) {
        'use strict';

        // initialize & populate view
        $scope.alert = '';
        $scope.errors = {};
        $scope.selectedElectionEventId = sessionService.getSelectedElectionEvent().id;
        $scope.selectedAuthority = null;
        $scope.noElectoralAuthoritySelected = true;
        $scope.electoralAuthorities = [];
        $scope.showMembersDialogTitle = '';
        $scope.votingCardSets = [];
        $scope.getSelecEAText = function() {
            return gettextCatalog.
            getString('Please select first a constituted Electoral authority');
        };

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

        // Called by the election-event-manage whenever it's necessary
        $scope.$on('refresh-authorities', function() {
            $scope.listElectoralAuthorities();
        });

        $scope.listElectoralAuthorities = function() {

            $scope.errors.getElectoralAuthoritiesFailed = false;
            $scope.selectedAuthority = null;

            var url = endpoints.host + endpoints.electoralAuthorities
                .replace('{electionEventId}', $scope.selectedElectionEventId);

            $http.get(url)
                .success(function(data) {
                    $rootScope.safeApply(function() {
                        $scope.electoralAuthorities = data.result;
                        sessionService.setElectoralAuthorities(data.result);
                    });
                })
                .error(function() {
                    $scope.errors.getElectoralAuthoritiesFailed = true;
                });

            var urlVotingCardSets = endpoints.host + endpoints.votingCardSets
                .replace('{electionEventId}', $scope.selectedElectionEventId);
            $http.get(urlVotingCardSets).
            success(function(data) {
            	$scope.votingCardSets = data.result;
            });
        };

        $scope.uniqueChoice = function(authorities, authority) {

            if (authority.selected) {

                authorities.forEach(function(a) {
                    if (a.id !== authority.id) {
                        a.selected = false;
                    }
                });
            }

            if (authority.selected) {
                $scope.selectedAuthority = authority;
                $scope.selectedAuthority.ready = false;
            } else {
                $scope.selectedAuthority = null;
            }

            sessionService.setSelectedElectoralAuthority($scope.selectedAuthority);


            $scope.electoralAuthorityMembers = [];
            $scope.electoralAuthorities.forEach(function(electoralAuthority) {

                if (electoralAuthority.id === authority.id) {
                    $scope.electoralAuthorityMembers = electoralAuthority.electoralBoard;
                }
            });

        };

        $scope.constitute = function() {

            if ($scope.selectedAuthority.status !== 'LOCKED') {
                new CustomDialog()
                    .title(gettextCatalog.getString('Constitute electoral authority'))
                    .cannotPerform(gettextCatalog.getString('Electoral Authority'))
                    .show();
                return;
            }


            var successCallback = function successCallback() {

                $scope.selectedAuthority.ready = true;
                sessionService.setSelectedElectoralAuthority($scope.selectedAuthority);

            };

            var errorCallback = function errorCallback() {
                new CustomDialog()
                    .title(gettextCatalog.getString('Constitute electoral authority'))
                    .error()
                    .show();
            };

            var url = (endpoints.host + endpoints.electoralAuthorityConstitute)
                .replace('{electionEventId}', $scope.selectedElectionEventId)
                .replace('{electoralAuthorityId}', $scope.selectedAuthority.id);

            $http.post(url).then(successCallback, errorCallback);

            sessionService.setNumberOfSuccessfullyWrittenSmartCards(0);
            $scope.listOfMembers = $scope.electoralAuthorityMembers;
            $scope.sharesType = 'electoralAuthorities';

            $scope.dialogPromise = $mdDialog.show({
                controller: DialogController,
                template: $templateCache.get(
                    'app/views/members-constitute/members-constitute.html'),
                parent: angular.element(document.body),
                clickOutsideToClose: false,
                scope: $scope,
                sessionService: sessionService,
                escapeToClose: false,
                preserveScope: true
            });

            $scope.dialogPromise.finally(function() {

                $scope.listElectoralAuthorities();

                if (sessionService.getNumberOfSuccessfullyWrittenSmartCards() ===
                    $scope.electoralAuthorityMembers.length) {

                    $mdToast.show(
                        toastCustom.topCenter(gettextCatalog.getString('Electoral Authority successfully constituted'), 'success')
                    );

                    sessionService.setNumberOfSuccessfullyWrittenSmartCards(0);
                    $scope.unselectAll();
                }
            });

        };

        $scope.showMembers = function(electoralAuthorityId, ev) {

            $scope.electoralAuthorityMembers = [];
            $scope.electoralAuthorities.forEach(function(electoralAuthority) {

                if (electoralAuthority.id === electoralAuthorityId) {

                    electoralAuthority.electoralBoard.forEach(function(electoralAuthorityMember) {
                        $scope.electoralAuthorityMembers.push(electoralAuthorityMember);
                    });
                }
            });
            $scope.showMembersDialogTitle =
                gettextCatalog.getString('Electoral Authority Members');
            $scope.listOfMembers = $scope.electoralAuthorityMembers;
            $mdDialog.show({
                controller: DialogController,
                template: $templateCache.get('app/views/dialogs/dialog-show-members.html'),
                parent: angular.element(document.body),
                targetEvent: ev,
                clickOutsideToClose: true,
                scope: $scope,
                escapeToClose: true,
                preserveScope: true
            });
        };

        $scope.isThereNoElectoralAuthoritySelected = function() {
            return !$scope.selectedAuthority;
        };

        $scope.getTextIsEASelected = function() {

            var check = $scope.isThereNoElectoralAuthoritySelected();
            return check ? $scope.getSelecEAText() : '';
        };

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

        var showSigningError = function() {
            new CustomDialog()
                .title('Electoral authority signing')
                .error()
                .show();
        };

        $scope.sign = function() {

            if ($scope.selectedAuthority.status !== 'READY') {
                new CustomDialog()
                    .title(gettextCatalog.getString('Electoral authority signing'))
                    .cannotPerform(gettextCatalog.getString('Electoral Authority'))
                    .show();
                return;
            }

            if (!$scope.isAdminAuthorityActivated()) {
                var p = $mdDialog.show(
                    $mdDialog.customConfirm({
                        locals: {
                            title: gettextCatalog.getString('Electoral authority signing'),
                            content: gettextCatalog.getString('Please, activate the administration board.'),
                            ok: gettextCatalog.getString('Activate now')
                        }
                    })
                );
                p.then(function (success) {
                    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()
                                .then(
                                    function(success){
                                        $scope.sign();
                                    }
                                );
                            }
                        }
                    );
                },
                function (error){
                    //Not possible to open the $mdDialog
                });
                return;
            }else{
                var electionEvent = sessionService.getSelectedElectionEvent();
                if (!sessionService.doesActivatedABBelongToSelectedEE()) {
                    $mdDialog.show(
                        $mdDialog.customAlert({
                            locals: {
                                title: gettextCatalog.getString('Wrong Administration Board activated'),
                                content: gettextCatalog.getString('The active Administration Board does not belong to the Election Event that you are trying to operate. Please deactivate it and activate the corresponding Administration Board for the Election Event') +' '+ electionEvent.defaultTitle + '.'
                            }
                        })
                    );
                    return;
                }
            }


            var privateKeyBase64 = sessionService.getSelectedAdminBoard().privateKey;

            var url = (endpoints.host + endpoints.electoralAuthoritySign)
                .replace('{electionEventId}', $scope.selectedElectionEventId)
                .replace('{electoralAuthorityId}', $scope.selectedAuthority.id);

            var body = { privateKeyPEM: privateKeyBase64 };

            $http.put(url, body)
                .success(function() {
                    $rootScope.safeApply(function() {
                        $mdToast.show(
                            toastCustom.topCenter(gettextCatalog.getString('Electoral authority signed!'), 'success')
                        );
                        $scope.listElectoralAuthorities();
                    });
                })
                .error(function() {
                    showSigningError();
                });

        };

        $scope.unselectAll = function() {
            $scope.electoralAuthorities.forEach(function(authority) {
                authority.selected = false;
            });
        };

        $scope.capitalizeFirstLetter = function(string) {
            var lowerCaseString = string.toLowerCase();
            return lowerCaseString.charAt(0).toUpperCase() + lowerCaseString.slice(1);
        };


        $scope.listElectoralAuthorities();
    });
