(function() {
    global.dashModule.directive('createUser', createUserDirective).controller('createUserCtrl', [
        '$scope',
        '$',
        '$http',
        '$translate',
        'utilsService',
        createUserCtrl
    ]);

    function createUserDirective() {
        return {restrict: 'E', templateUrl: 'users/html/createUserTemplate'};
    }

    function createUserCtrl($scope, $, $http, $translate, utilsService) {
        let commercialLeadKeyDropped;
        let listSelector;
        $scope.isSelectCLVisible = isSelectCLVisible;
        $scope.info = {};
        $scope.roles = [];
        $scope.selectedUserType = '';
        $scope.startEventStyle = startEventStyle;
        $scope.endEventStyle = endEventStyle;
        $scope.droppedCommercialLead = droppedCommercialLead;
        $scope.saveUserInDB = saveUserInDB;
        $scope.getUserTypes = getUserTypes;
        $scope.checkIfCLIsNeeded = checkIfCLIsNeeded;
        $scope.getDataForUserCreation = getDataForUserCreation;
        $scope.selectCompany = selectCompany;
        $scope.selectedCompany = '';
        $scope.toggleNewCompany = toggleNewCompany;
        $scope.showAddNewCompany = false;
        $scope.getClassForCompany = getClassForCompany;

        function getDataForUserCreation() {
            getUserTypes();
            getCompanies();
        }

        function getUserTypes() {
            $http({method: 'POST', url: 'users/api/getUserTypes'}).then(setUserTypes, utilsService.onHttpError);
        }

        function setUserTypes(response) {
            $scope.roles = response.data || [];
            if ($scope.selectedUserType) {
                const selectedUserType = $scope.roles.find(role => {
                    return role.name === $scope.selectedUserType;
                });

                $scope.userTypeSelected = {
                    id: selectedUserType.id
                };
            }
        }

        function getCompanies() {
            $http({
                method: 'GET',
                url: 'users/api/getCompanies'
            }).then(setCompanies, utilsService.onHttpError);
        }

        function setCompanies(response) {
            $scope.availableCompanies = response.data || [];
            if ($scope.selectedCompany) {
                const selectedCompany = $scope.availableCompanies.find(company => {
                    return company.name === $scope.selectedCompany;
                });

                $scope.companySelected = {
                    id: selectedCompany.id
                };
            }
        }

        function selectCompany(selectedCompany = '') {
            $scope.selectedCompany = selectedCompany;
        }

        function checkIfCLIsNeeded(selectedUserType = '') {
            $scope.selectedUserType = selectedUserType;
            if ($scope.userTypeSelected.id === '2') {
                getCommercialLeads();
            }
        }

        function getCommercialLeads() {
            $http({method: 'GET', url: 'users/api/getCommercialLeads'}).then(setCommercialLeads, utilsService.onHttpError);
        }

        function setCommercialLeads(response) {
            if (response.data) {
                $scope.availableCommercialLeads = response.data;
                $scope.selectedCommercialLeads = [];
            }
        }

        function isSelectCLVisible() {
            return $scope.userTypeSelected && $scope.userTypeSelected.name
                ? $scope.userTypeSelected.name.toLowerCase() === 'customer'
                : false;
        }

        function saveUserInDB() {
            $scope.info.idUserType = $scope.userTypeSelected && $scope.userTypeSelected.id
                ? $scope.userTypeSelected.id
                : 0;

            if(!$scope.showAddNewCompany) {
                $scope.info.selectedCompanyId = $scope.companySelected ? $scope.companySelected.id : 0;
                delete $scope.info.companyName;
                delete $scope.info.vat;
            }
            const params = $.param({
                info: JSON.stringify($scope.info),
                cl: JSON.stringify($scope.selectedCommercialLeads)
            });

            $http({
                method: 'POST',
                data: params,
                url: 'users/api/saveUserInDB'
            }).then(showConfirmationMessage, utilsService.onHttpError);
        }

        function showConfirmationMessage(response) {
            if (response.data && response.data.messages) {
                const messagesData = response.data.messages;
                messagesData.forEach(messageData => {
                    const message = $translate.instant('users.forms.messages.' + messageData.message);
                    utilsService.displayMessage(messageData.code, message);
                    if (messageData.code === 'success') {
                        $scope.info = {};
                        checkIfCLIsNeeded();
                        if($scope.showAddNewCompany) {
                            getCompanies();
                            toggleNewCompany();
                        }
                    }
                });
            }
        }

        function startEventStyle(event, ui, from, key) {
            $('.choose-cl-list').css({overflow: 'visible'});

            switch (from) {
            case 'available':
                $('#selected-cl-list-container').addClass('allowed-drop-zone');
                break;
            case 'selected':
                $('#available-cl-list-container').addClass('allowed-drop-zone');
                break;
            default:
                break;
            }

            commercialLeadKeyDropped = key;
            listSelector = from;
        }

        function endEventStyle() {
            $('.choose-cl-list').css({'overflow-y': 'scroll'});
            $('.choose-cl-list').removeClass('allowed-drop-zone');
        }

        function droppedCommercialLead(event, ui, from) {
            if (from !== listSelector) {
                if (listSelector === 'available') {
                    $scope.selectedCommercialLeads.push($scope.availableCommercialLeads[commercialLeadKeyDropped]);
                    $scope.availableCommercialLeads.splice(commercialLeadKeyDropped, 1);
                } else if (listSelector === 'selected') {
                    $scope.availableCommercialLeads.push($scope.selectedCommercialLeads[commercialLeadKeyDropped]);
                    $scope.selectedCommercialLeads.splice(commercialLeadKeyDropped, 1);
                }
            }
            $(ui.helper).css({position: 'relative', left: 0, top: 0});
        }

        function toggleNewCompany() {
            $scope.showAddNewCompany = !$scope.showAddNewCompany;
        }

        function getClassForCompany() {
            return $scope.showAddNewCompany ? 'select-inactive' : '';
        }
    }
})();
