/*jslint node: true */
/*jslint browser: true*/
/*jslint nomen: true*/
/*global BaseController, angular, $*/

'use strict';

var hubManagementController = BaseController.extend({
    /**
     * Initialize  Controller
     * @param $scope, current controller scope
     */
    init: function ($scope, $modal, hubManagementService, actionHelper) {
        let self = this;

        this._super($scope);
        this.$modal = $modal;
        this.hubManagementService = hubManagementService;
        this.actionHelper = actionHelper;

        this.$scope.connectedHubs = [];
        common.globalSpinner.show();

        this.hubManagementService.gethubStatus().then(function (response) {
            self.$scope.hubStatus = response.data;
        }).catch(function (error) {
            self.showError(error.data);
        });

        let showPage = function () {
            common.globalSpinner.hide();
            $('main[ng-app="hubManagementApp"]').show();
        }

        this.hubManagementService.getHubInfo().then(function (response) {
            self.$scope.hubInfo = response.data;
            showPage();
        }).catch(function (error) {
            self.showError(error.data);
            showPage();
        });
    },

    defineScope: function () {
        this.$scope.instance = "indexController";
        this.$scope.enableSuperhub = this.enableSuperhub.bind(this);
        this.$scope.enableFeeder = this.enableFeeder.bind(this);
        this.$scope.openConnectHubModal = this.openConnectHubModal.bind(this);
        this.$scope.loadConnectedHubs = this.loadConnectedHubs.bind(this);
    },
    defineListeners: function () {
        // define self variable to use `this` in the inner anonymous function scope
        let self = this;
        this.$scope.$watch('hubStatus.role', function (role) {
            if (role === 'feeder') {
                self.hubManagementService.getSuperHub().then(function (response) {
                    self.$scope.superHubData = (response.data === 'null' ? null : response.data);
                }).catch(function (error) {
                    self.showError(error.data);
                });
            } else {
                self.loadConnectedHubs();
            }
        });
    },

    loadConnectedHubs: function () {
        let self = this;
        this.hubManagementService.getRemoteHubs().then(function (response) {
            self.$scope.connectedHubs = [];
            Object.keys(response.data).forEach(function (key) {
                self.$scope.connectedHubs.push(response.data[key]);
            });
        }).catch(function (error) {
            self.showError(error.data);
        });
    },

    enableSuperhub: function () {
        let self = this;
        this.modalInstance = this.$modal.open({
            templateUrl: 'confirmSuperHubEnabling.html',
            backdrop: 'static',
            keyboard: true,
            windowClass: 'enable-superhub-modal',
            controller: function ($scope, $modalInstance, $parent) {
                $scope.close = function () {
                    $modalInstance.close('cancel');
                };

                $scope.enable = function () {
                    common.globalSpinner.show();
                    $parent.hubManagementService.enableSuperhub().then(
                        () => {
                            common.globalSpinner.hide();
                            document.location.reload();
                        },
                        () => {
                            // the agent run that will happen after a super hub is enabled will reload apache
                            // that causes an error (connection will be closed) and we need to reload page when it happens
                            common.globalSpinner.hide();
                            setTimeout(()=> document.location.reload(), 2000);
                        });
                    $parent.$scope.hubStatus.enable_request_sent = true;
                    $modalInstance.close('cancel');
                };
            },
            resolve: {
                $parent: function () {
                    return self;
                }
            }
        });
    },

    enableFeeder: function () {
        let self = this;
        common.globalSpinner.show();
        this.hubManagementService.enableFeeder().then(() => {
            self.actionHelper.triggerHubsAgentRun().then(
                () => {
                    common.globalSpinner.hide();
                    document.location.reload();
                },
                (error) => {
                    self.showError(error.data);
                    common.globalSpinner.hide();
                })
        });
        this.$scope.hubStatus.enable_request_sent = true;
    },

    showError: function (message) {
        notify.error(message);
    },

    openConnectHubModal: function (id = null) {
        let self = this;
        this.modalInstance = this.$modal.open({
            templateUrl: 'connectHubModal.html',
            backdrop: 'static',
            keyboard: true,
            windowClass: 'hub-management',
            controller: function ($scope, $modalInstance, $parent, $id) {
                setTimeout(processPageBeforeLeave, 1000);
                let self = this;
                $scope.modalData = {};
                $scope.isEditOperation = false;
                $scope.formData = {enabled: true};
                $scope.authCodeRequired = false;

                $scope.transports = [
                    {'label': 'pull over rsync/ssh', 'value': 'pull_over_rsync'},
                    {'label': 'push over rsync/ssh', 'value': 'push_over_rsync'}
                ];

                $scope.$watch('formData.enabled', function (enabled) {
                    $scope.formData.target_state = (enabled === true ? 'on' : 'paused');
                });

                $scope.$on('sshKeyLoad', function (event, data) {
                    $scope.formData.sshKey = data;
                });

                $scope.close = function () {
                    $modalInstance.close('cancel');
                    unbindBeforeUnload();
                };

                if ($id != null && $id > 0) {
                    $parent.hubManagementService.getRemoteHub($id).then(
                        function (response) {
                            $scope.formData = response.data;
                            $scope.formData.transport_method = {value : $scope.formData.transport.mode};
                            $scope.formData.enabled = ($scope.formData.target_state != undefined && $scope.formData.target_state == 'on' ? true : false);
                            $scope.isEditOperation = true;
                            setTimeout(processPageBeforeLeave, 1000)
                        }).catch(function (error) {
                            self.showError(error.data);
                    });
                }

                $scope.validate = function () {
                    $scope.validationErrors = {};

                    if ($scope.formData.userName == undefined || $scope.formData.userName == '') {
                        $scope.validationErrors.userName = 'required field';
                    }

                    if ($scope.formData.password == undefined || $scope.formData.password == '') {
                        $scope.validationErrors.password = 'required field';
                    }

                    let regex = /(https):\/\//;
                    if (!regex.test($scope.formData.api_url)) {
                        $scope.validationErrors.api_url = 'Invalid url. Only https:// URLs are allowed';
                    }

                }

                $scope.connectHub = function (closeModal = true) {
                    $scope.validate();
                    $scope.closeModal = closeModal;
                    if (Object.keys($scope.validationErrors).length > 0) {
                        return false;
                    }
                    common.globalSpinner.show();
                    $parent.hubManagementService.addFeeder($scope.formData).then(
                        function (response) {
                            common.globalSpinner.hide();
                            //reset api url
                            $scope.formData.api_url = '';
                            notify.success('Hub was successfully connected.');
                            $parent.loadConnectedHubs();

                            if (closeModal === true) {
                                $scope.close();
                            }
                            // clear form after a feeder was added
                            $scope.sslCertError = null;
                            $scope.formData = {enabled: true, target_state: 'on'};
                        }).catch(function (error) {
                            if (error.data.hasOwnProperty('error') && error.data.error === 'ssl_cert') {
                                $scope.sslCertError = {
                                    certInfo: error.data.data
                                };
                            } else if ($parent._is2FaRequired(error.data)) {
                                $scope.authCodeRequired = true;
                                $parent.showError(error.data.trim());
                            } else  {
                                $parent.showError(error.data.trim());
                            }

                            common.globalSpinner.hide();
                        });
                };

                $scope.editHub = function () {
                    $scope.validate();
                    if (Object.keys($scope.validationErrors).length > 0) {
                        return false;
                    }

                    $scope.authCodeRequired = false;
                    
                    common.globalSpinner.show();
                    $parent.hubManagementService.editFeeder($id, $scope.formData).then(function (response) {
                        common.globalSpinner.hide();
                        $scope.formData = {enabled: true, target_state: 'on'};
                        notify.success('Hub was successfully updated.');
                        $parent.loadConnectedHubs();
                        $scope.close();
                    }).catch(function (error) {
                        if (error.data.hasOwnProperty('error') && error.data.error === 'ssl_cert') {
                            $scope.sslCertError = {
                                certInfo: error.data.data
                            };
                        } else if ($parent._is2FaRequired(error.data)) {
                            $scope.authCodeRequired = true;
                            $parent.showError(error.data.trim());
                        } else  {
                            $parent.showError(error.data.trim());
                        }

                        common.globalSpinner.hide();
                    });
                };
            },
            resolve: {
                $parent: function () {
                    return self;
                },
                $id: function () {
                    return id;
                },
            }
        });
    },
    
    _is2FaRequired: error => error.startsWith('Invalid two-factor')
});


hubManagementController.$inject = ['$scope', '$modal', 'hubManagementService', 'actionHelper'];

hubManagementApp.controller('hubManagementController', hubManagementController);
