/*
 * 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
 */
(function() {

    'use strict';

    /*jshint maxparams: 13 */
    angular.module('election-event-list', ['ui.router', 'app.sessionService', 'endpoints'])
        .controller('election-event-list', function(
            $scope,
            $rootScope,
            sessionService,
            endpoints,
            $http,
            $state,
            $mdDialog,
            $q,
            $mdToast,
            toastCustom,
            CustomDialog,
            InProgress,
            gettextCatalog,
            ErrorsDict,
            entitiesCounterService
        ) {


            var alreadySynched = false;

            $scope.data = {};

            $scope.selectEEText = function() {
                return gettextCatalog.
                    getString('Please select first an Election event with a constituted Administration board');
            };
            $scope.listElectionEvents = function() {

                $scope.errors = {};

                $http.get(endpoints.host + endpoints.electionEvents).
                    success(function(data) {
                        $scope.selectedElectionEvent = null;
                        try {
                            sessionService.setElectionEvents(data);
                            $scope.electionEvents = data;
                            $scope.checkAutoSynch();

                        } catch (e) {
                            $scope.data.message = e.message;
                            $scope.errors.electionEventsFailed = true;
                        }

                    }).
                    error(function() {
                        $scope.errors.electionEventsFailed = true;
                    });
                    
            };

            $scope.isABConstituted = function(adminBoardId) {

                var result;
                sessionService.getAdminBoards().forEach(function(adminBoard) {
                    if (adminBoard.id === adminBoardId) {

                        result = adminBoard.status === 'CONSTITUTED';
                    }
                });
                return result;
            };

            /*
            Lauch the endpoint responsible of generating the configuration of
            a given election event
            */
            $scope.generate = function() {

                if ($scope.selectedElectionEvent.status !== 'LOCKED') {
                    new CustomDialog()
                        .title(gettextCatalog.getString('Secure election event'))
                        .cannotPerform(gettextCatalog.getString('Election Event'))
                        .show();
                    return;
                }

                if (!$scope.isABConstituted($scope.selectedElectionEvent.administrationAuthority.id)) {
                    $mdDialog.show(
                        $mdDialog.customAlert({
                            locals: {
                                title: gettextCatalog.getString('Secure election event'),
                                content: gettextCatalog.getString('Only election events with a constituted administration board can be secured')
                            }
                        })
                    );
                    return;
                }

                $scope.errors = {};

                if ($scope.selectedElectionEvent) {

                    if (!InProgress.contains($scope.selectedElectionEvent.id)) {
                        InProgress.init($scope.selectedElectionEvent.id);
                        try {
                            var url = endpoints.electionEvent.replace(
                                '{electionEventId}', $scope.selectedElectionEvent.id);
                            $mdToast.show(
                                toastCustom.topCenter(gettextCatalog.getString('Election Event securization started...'), 'success')
                            );
                            $http.post(endpoints.host + url).
                                success(function() {
                                    $http.get(endpoints.host + url).
                                        success(function() {
                                            InProgress.finish($scope.selectedElectionEvent.id);
                                            $mdToast.show(
                                                toastCustom.topCenter(gettextCatalog.getString('Election Event secured'), 'success')
                                            );
                                            $rootScope.$broadcast('refresh-election-events');
                                        });
                                }).
                                error(function(data) {
                                    InProgress.finish($scope.selectedElectionEvent.id);
                                    $scope.data.message = JSON.stringify(data);
                                    new CustomDialog()
                                        .title(gettextCatalog.getString('Secure election event'))
                                        .error()
                                        .show();
                                });
                        } catch (e) {
                            InProgress.finish($scope.selectedElectionEvent.id);
                            $scope.data.message = e;
                            new CustomDialog()
                                .title(gettextCatalog.getString('Secure election event'))
                                .error()
                                .show();
                        }
                    } else {
                        $mdDialog.show(
                            $mdDialog.customAlert({
                                locals: {
                                    title: gettextCatalog.getString('Secure election event'),
                                    content: gettextCatalog.getString('Securization of this election event is in progress')
                                }
                            })
                        );
                    }
                }
            };

            $scope.goToElectionEvent = function(electionEvent) {

                $scope.errors = {};
                if (electionEvent.status === 'READY') {
                    sessionService.setSelectedElectionEvent(electionEvent);
                    $state.go('ballots');
                } else {
                    $mdDialog.show(
                        $mdDialog.customAlert({
                            locals: {
                                title: gettextCatalog.getString('View Election Event(s)'),
                                content: gettextCatalog.getString('To manage election events you have to secure them first.' +
                                    ' To do this, select election events from the list and click on' +
                                    ' the "SECURE" action button above.')
                            }
                        })
                    );
                    return;
                }
            };

            $scope.checkAutoSynch = function() {

                // perform autosynch if needed


                if(sessionService.isSync()) {
                    alreadySynched = true;
                }

                if (!alreadySynched &&
                    (!$scope.electionEvents ||
                        !$scope.electionEvents.result ||
                        $scope.electionEvents.result.length === 0)) {

                    alreadySynched = true;
                    $scope.synchronize();
                }

            };


            $scope.uniqueChoice = function(electionEvents, electionEvent) {

                $scope.errors = {};

                var selectedEE = null;

                if (electionEvent.chosen) {

                    electionEvents.forEach(function(o) {
                        if (o.id !== electionEvent.id) {
                            o.chosen = false;
                        } else {
                            selectedEE = o;

                        }
                    });
                }

                if (electionEvent.chosen) {
                    $scope.selectedElectionEvent = selectedEE;
                } else {
                    $scope.selectedElectionEvent = null;
                }

                sessionService.setSelectedElectionEvent(selectedEE);

            };

            $scope.checkSelected = function() {
                return !$scope.selectedElectionEvent ||
                    $scope.selectedElectionEvent.status !== 'LOCKED';
            };

            $scope.checkSelectedDownload = function() {
                return !$scope.selectedElectionEvent || $scope.selectedElectionEvent.status !== 'READY';
            };
            
            $scope.downloadParticipationEnabled = function() {
                return sessionService.isDownloadParticipationEnabled();
            };
            
            $scope.importExportEnabled = function() {
                return sessionService.isImportExportEnabled();
            };

            $scope.getTextIsEESelected = function() {
                var check = $scope.checkSelected();
                return check ? $scope.selectEEText : '';
            };

            $scope.getAdminBoardTitle = function(adminBoardId) {

                var adminBoardTitle = '';
                (sessionService.getAdminBoards() || []).forEach(function(adminBoard) {
                    if (adminBoard.id === adminBoardId) {
                        adminBoardTitle = adminBoard.defaultTitle;
                    }
                });

                return adminBoardTitle;
            };

            //Not used now, but will be used as other US defines
            $scope.isNotReadyToNavigate = function(electionEvent) {

                return electionEvent.status !== 'READY';
            };

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

            var showParticipationFileDownloadError = function() {
                new CustomDialog()
                    .title(gettextCatalog.getString('Participation file download'))
                    .error()
                    .show();
            };

            $scope.downloadParticipationFile = function(ev) {

                $scope.errors.participationFileDownloadError = false;

                // no selection?

                if (!$scope.selectedElectionEvent) {
                    $mdDialog.show(
                        $mdDialog.customAlert({
                            locals: {
                                title: gettextCatalog.getString('Participation file download'),
                                content: (gettextCatalog.getString('Please, select an election event to download the participation file.'))
                            }
                        })
                    );
                    return;
                }

                if ($scope.selectedElectionEvent.status !== 'READY') {
                    new CustomDialog()
                        .title(gettextCatalog.getString('Participation file download'))
                        .cannotPerform(gettextCatalog.getString('Election Event(s)'))
                        .show();
                    return;
                }

                // download participation file

                var url = (endpoints.host + endpoints.participation)
                    .replace('{electionEventId}', $scope.selectedElectionEvent.id);

                $http({
                    method: 'GET',
                    url: url
                }).then(function() {
                    $mdToast.show(
                        toastCustom.topCenter(gettextCatalog.getString('Participation file downloaded!'), 'success')
                    );
                    $scope.selectedElectionEvent.chosen = false;
                    $scope.selectedElectionEvent = null;
                }, function() {
                    $scope.errors.participationFileDownloadError = true;
                    showParticipationFileDownloadError(ev);
                });
            };

            $scope.checkOneSelected = function() {
                return !$scope.selectedElectionEvent;
            };
            
            $scope.export = function (path) {
                $scope.includeElectoralEvent = false;
                $scope.includeVotingCards = false;
                $scope.includeCustomerSpecific = false;
                $mdDialog.show({
                    controller: function($scope, $mdDialog) {
                        $scope.exportError = false;
                        $scope.exportCancel = function() {
                            $mdDialog.cancel();
                        };
                        $scope.exportDoExport = function(answer) {
                            $scope.exportError = 
                                !$scope.includeElectoralEvent &&
                                !$scope.includeVotingCards &&
                                !$scope.includeCustomerSpecific;
                            if ( !$scope.exportError ) {
                                $mdDialog.hide(true);
                            } 
                        };
                    },
                    templateUrl: 'app/views/dialogs/dialog-export-election-event.html',
                    parent: angular.element(document.body),
                    scope: $scope,
                    clickOutsideToClose: false,
                    escapeToClose: true,
                    preserveScope: true
                })
                    .then(function () {
                        var url = endpoints.host + endpoints.export
                            .replace('{electionEventId}', $scope.selectedElectionEvent.id);
                        var body = {
                            path: path,
                            electionEventData: $scope.includeElectoralEvent,
                            computedChoiceCodes: $scope.includeElectoralEvent,
                            ballotBoxes: $scope.includeElectoralEvent,
                            preComputedChoiceCodes: $scope.includeElectoralEvent,
                            votingCardsData: $scope.includeVotingCards,
                            customerData: $scope.includeCustomerSpecific
                        };
                    
                        $scope.title = gettextCatalog.getString('Exporting...');
                    
                        $mdDialog.show({
                            scope: $scope,
                            preserveScope: true,
                            templateUrl: 'app/views/dialogs/dialog-custom-progress-template.html',
                            escapeToClose: false,
                            parent: angular.element(document.body)
                        });
                    
                        $http.post(url, body)
                            .then(function (res) {
                                $mdDialog.hide();
                                $mdToast.show(
                                    toastCustom.topCenter(gettextCatalog.getString('Data exported successfully'), 'success')
                                );
                            })
                            .catch(function (e) {
                                $mdDialog.hide();
                                if(e.data.error=='4005') {
                                    $mdDialog.show(
                                        $mdDialog.customAlert({
                                            locals: {
                                                title: gettextCatalog.getString('Data has not been exported'),
                                                content: gettextCatalog.getString(ErrorsDict(e.data.error))
                                            }
                                        })
                                    );
                                } else {
	                        $mdToast.show(
                                        toastCustom.topCenter(
                                            gettextCatalog.getString('Export') + ': ' + 
                                    gettextCatalog.getString('Something went wrong. Contact with Support') + '. ' +
                                    gettextCatalog.getString('Error code') + ': ' + e.data.error + ', ' +
                                    gettextCatalog.getString(ErrorsDict(e.data.error)),
                                            'error'
                                        )
	                        );
                                }
                            });
                    });
            };


            $scope.listElectionEvents();

            $scope.$on('refresh-election-events', function() {
                $scope.listElectionEvents();
            });

        });

})();
