(function () {
    global.dashModule
        .controller('packagesController', ['$scope', '$http', '$', '$translate', '$rootScope', '$compile', 'dataTableHelper', 'utilsService', packagesController])
        .directive('packages', [packagesDirective]);

    function packagesDirective() {
        return {
            restrict: 'E',
            templateUrl: 'packages/html/PackagesTemplate'
        };
    }

    function packagesController($scope, $http, $, $translate, $rootScope, $compile, dataTableHelper, utilsService) {
        const translationPath = 'packages.tables.headers.';
        let userType = 'none';
        $scope.subModule = global.getParameterByName('subModule') || 'packages';
        $scope.setSubModule = setSubModule;
        $scope.isSubmoduleVisible = isSubmoduleVisible;
        $scope.getPackages = getPackages;
        $scope.getMyPackages = getMyPackages;
        addUrlListener();

        function addUrlListener() {
            window.addEventListener('popstate', function (e) {
                $scope.$evalAsync($scope => {
                    $scope.subModule = e.state ? e.state.subModule : 'packages';
                });
            }, false);
        }

        function setSubModule($event) {
            $scope.subModule = $event.currentTarget.attributes.subModule.value;
            history.pushState({
                subModule: $scope.subModule
            }, null, '?subModule=' + $scope.subModule);
        }

        function isSubmoduleVisible(subModule) {
            return subModule === $scope.subModule;
        }

        function getPackages() {
            $http({
                method: 'POST',
                url: 'packages/api/getPackagesHeaders'
            }).then(showPackages, utilsService.onHttpError);
        }

        function showPackages(response) {
            if (typeof response.data.headers !== 'undefined') {
                userType = response.data.userType || 'none';
                const params = {
                    selector: '#packages-tabel',
                    url: 'packages/api/getPackages',
                    hasDetails: true,
                    extraTableOptions: {
                        responsive: false,
                        order: [
                            [1, 'asc']
                        ]
                    }
                };
                dataTableHelper.generateColumns(response.data.headers, translationPath, dataTableHelper.showTable, params, formatPackagesColumn)
                    .then((table) => {
                        addDetailsEvent(table, params.selector, 'packages-details');
                    });
            }
        }

        function getMyPackages() {
            $http({
                method: 'POST',
                url: 'packages/api/getMyPackagesHeaders'
            }).then(showMyPackages, utilsService.onHttpError);
        }

        function showMyPackages(response) {
            if (typeof response.data.headers !== 'undefined') {
                userType = response.data.userType || 'none';
                const params = {
                    selector: '#my-packages-tabel',
                    url: 'packages/api/getMyPackages',
                    hasDetails: true,
                    extraTableOptions: {
                        responsive: false,
                        order: [
                            [1, 'asc']
                        ]
                    }
                };
                dataTableHelper.generateColumns(response.data.headers, translationPath, dataTableHelper.showTable, params, formatPackagesColumn)
                    .then((table) => {
                        addDetailsEvent(table, params.selector, 'my-packages-details');
                    });
            }
        }

        function addDetailsEvent(table, containerSelector, directiveName) {
            $(containerSelector + ' tbody').off('click', 'td.info-control');
            $(containerSelector + ' tbody').on('click', 'td.info-control', function () {
                var tr = $(this).closest('tr');
                var row = table.row(tr);

                if (row.child.isShown()) {
                    row.child.hide();
                    tr.removeClass('shown');
                } else {
                    const ctrl = directiveName === 'packages-details' ? 'packagesDetailsCtrl' : 'myPackagesDetailsCtrl';
                    const directiveHtml = '<'+directiveName+' ng-controller="'+ctrl+'"></'+directiveName+'>';
                    const scope = $rootScope.$new();
                    scope.data = row.data();
                    const layerSelector = 'details-layer-' + scope.data.id;
                    row.child('<div id="' + layerSelector + '"></div>').show();

                    const comp = $compile($(directiveHtml))(scope);
                    $('#' + layerSelector).append(comp);
                    tr.addClass('shown');
                }
            });
        }

        function formatPackagesColumn(value, translations) {
            const columnObj = {
                data: value,
                title: translations[translationPath + value]
            };
            const renders = getPackageRenders(value);

            columnObj.visible = isColumnVisible(value);

            if (typeof renders[value] !== 'undefined') {
                columnObj.render = renders[value];
            }

            return columnObj;
        }

        function isColumnVisible(value) {
            const notVisibleFields = [
                'prices',
                'status',
                'idCountry',
                'countryCode',
                'additionalInstallationDays',
                'idPackageType',
                'description',
                'extraPackages',
                'products',
                'documents'
            ];

            return notVisibleFields.indexOf(value) === -1;
        }

        function getPackageRenders() {
            return {
                products: packagesReplaceCommaRenderer,
                processes: showProcesses,
                name: packagesNameRenderer,
                isPriceSet: packagesIsPriceSetRenderer,
                hasDocuments: packagesHasDocumentsRenderer
            };

            function packagesHasDocumentsRenderer(data, type, row) {
                let html = '';
                row.documents.forEach((documentObj) => {
                    html += '<div class="package-documents">';
                    html += '<a href="utils/api/downloadFile?idDocument='+documentObj.idDocument+'&fileName='+documentObj.documentName+'.' +documentObj.extension+'">';
                    html += documentObj.documentName + '.' + documentObj.extension;
                    html += '</a>';
                    html += '</div>';
                });

                return html;
            }

            function packagesReplaceCommaRenderer(data) {
                return data.replace(/,/g, '<br/>');
            }

            function showProcesses(data){
                let html = '';

                if(data.length > 0){
                    html += '<details>';
                    html += '<summary>'+$translate.instant('packages.tables.extra.SEE_PROCESS')+'</summary>';
                    data.forEach((process) => {
                        html += '<p>' + process.processName + '</p>';
                    });
                    html += '</details>';
                }else{
                    html = '-';
                }

                return html;
            }

            function packagesNameRenderer(data, type, row) {
                if (userType === 'commercial_lead' && $scope.subModule === 'myPackages') {
                    const sellMessage = row.status === 'available' ? $translate.instant('packages.tables.extra.EDIT') : $translate.instant('packages.tables.extra.NOT_AVAILABLE');
                    let newData = '<a id="edit-price-' + row.id + '" href="packages?subModule=selectPackage&idPackage=' + row.id + '">';
                    newData += row.status === 'available' ?
                        data + ' (' + sellMessage + ')' :
                        data + ' (<div class="unavailable-products"><span class="glyphicon glyphicon-warning-sign"></span>' + sellMessage + '</div>)';
                    newData += '</a>';

                    return newData;
                }

                return data;
            }

            function packagesIsPriceSetRenderer(data, type, row) {
                let priceText = '';

                if (userType === 'broker') {
                    if (row.status === 'not-available') {
                        priceText = '<a id="set-price-' + row.id + '" href="packages?subModule=editPackages&idCountry=' + row.idCountry + '&idPackage=' + row.id + '">';
                        priceText += '<div class="unavailable-products">';
                        priceText += '<span class="glyphicon glyphicon-ban-circle"></span> ';
                        priceText += $translate.instant('packages.tables.extra.PRODUCTS_NOT_AVAILABLE');
                        priceText += '</div>';
                        priceText += '</a>';
                    } else if (row.processes.length === 0) {
                        priceText += '<div class="set-price-text">';
                        priceText += '<span class="glyphicon glyphicon-info"></span>';
                        priceText += $translate.instant('packages.tables.extra.NO_PROCESS_SET');
                        priceText += '</div>';
                    } else {
                        if (data === '0') {
                            priceText = '<div class="set-price-text">';
                            priceText += ' <span class="glyphicon glyphicon-euro"></span><span class="glyphicon glyphicon-remove small-price-icon"></span> ';
                            priceText += $translate.instant('packages.tables.extra.SET_PRICE');
                            priceText += '</div>';
                        } else {
                            priceText = '<div class="edit-price-text">';
                            priceText += '<span class="glyphicon glyphicon-euro"></span><span class="glyphicon glyphicon-ok small-price-icon"></span> ';
                            priceText += $translate.instant('packages.tables.extra.EDIT_PRICE');
                            if (row.status === 'high-cost') {
                                priceText += '<div class="margin-exceded">';
                                priceText += '<span class="glyphicon glyphicon-warning-sign"></span> ';
                                priceText += $translate.instant('packages.tables.extra.MARGIN_EXCEDED');
                                priceText += '</div>';
                            }
                            priceText += '</div>';
                        }

                        priceText = '<a id="set-price-' + row.id + '" href="packages?subModule=setPackagePrice&idPackage=' + row.id + '">' + priceText + '</a>';
                    }

                    return priceText;
                }

                if (userType === 'commercial_lead') {
                    priceText = '<div class="set-price-text">';
                    priceText += ' <span class="glyphicon glyphicon-euro"></span><span class="glyphicon glyphicon-ok small-price-icon"></span> ';
                    priceText += $translate.instant('packages.tables.extra.SELL_THIS');
                    priceText += '</div>';
                    return '<a id="sell-this-' + row.id + '" href="packages?subModule=selectPackage&idPackage=' + row.id + '">' + priceText + '</a>';
                }

                return data;
            }
        }

    }
})();
