(function () {
    global.dashModule
        .controller('suppliersController', ['$scope', '$rootScope', '$compile', '$http', '$', 'dataTableHelper', 'utilsService', suppliersController])
        .directive('suppliers', [suppliersDirective]);

    function suppliersDirective() {
        return {
            restrict: 'E',
            templateUrl: 'suppliers/html/suppliersTemplate'
        };
    }

    function suppliersController($scope, $rootScope, $compile, $http, $, dataTableHelper, utilsService) {
        const translationPath = 'suppliers.tables.headers.';
        $scope.subModule = 'suppliers';
        $scope.setSubModule = setSubModule;
        $scope.isSubmoduleVisible = isSubmoduleVisible;
        $scope.getSuppliers = getSuppliers;
        $scope.getSuppliersProducts = getSuppliersProducts;

        function setSubModule($event) {
            $scope.subModule = $event.currentTarget.attributes.subModule.value;
        }

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

        function getSuppliersProducts() {
            $http({
                method: 'GET',
                url: 'suppliers/api/getSuppliersProductsHeaders'
            }).then(showSuppliersProducts, utilsService.onHttpError);
        }

        function showSuppliersProducts(response) {
            if (response.data.length > 0) {
                const params = {
                    selector: '#suppliers-products',
                    url: 'suppliers/api/getSuppliersProducts',
                    hasEdit: true,
                    extraTableOptions: {
                        responsive: false,
                        order: [
                            [1, 'asc']
                        ]
                    }
                };
                dataTableHelper.generateColumns(response.data, translationPath, dataTableHelper.showTable, params, formatSuppliersProductsColumn)
                    .then((table) => {
                        addEditEvent(table, params.selector, 'suppliers-products-add-edit', 'suppliersProductsAddEditCtrl', getSuppliersProducts);
                        addShowDocumentsEvent(table, params.selector, getSuppliersProducts);
                    });
            }
        }

        function getSuppliers() {
            $http({
                method: 'GET',
                url: 'suppliers/api/getSuppliersHeaders',
            }).then(showSuppliers, utilsService.onHttpError);
        }

        function showSuppliers(response) {
            if (response.data.length > 0) {
                const params = {
                    selector: '#suppliers',
                    url: 'suppliers/api/getSuppliers',
                    hasEdit: true,
                    extraTableOptions: {
                        responsive: false,
                        order: [
                            [1, 'asc']
                        ]
                    }
                };
                dataTableHelper.generateColumns(response.data, translationPath, dataTableHelper.showTable, params, formatSuppliersColumn)
                    .then((table) => {
                        addEditEvent(table, params.selector, 'suppliers-add-edit', 'suppliersAddEditCtrl', getSuppliers);
                    });
            }
        }

        function addShowDocumentsEvent(table, containerSelector, callback) {
            $(containerSelector + ' tbody').off('click', 'td.show-documents');
            $(containerSelector + ' tbody').on('click', 'td.show-documents', function () {
                var tr = $(this).closest('tr');
                var row = table.row(tr);

                if (row.child.isShown()) {
                    row.child.hide();
                    tr.removeClass('shown');
                } else {
                    const newScope = $rootScope.$new();
                    newScope.data = $.extend(true, {}, row.data());
                    const directiveHtml = '<show-product-documents class="product-documents" ng-controller="showProductDocumentsCtrl" ></show-product-documents>';
                    const layerId = newScope.data.idProduct + '-' + newScope.data.idSupplier + '-' + newScope.data.idCountry;
                    newScope.formAction = 'EDIT';
                    newScope.onUpdated = callback;
                    const layerSelector = 'edit-layer-' + layerId;
                    row.child('<div class="edit-tr" id="' + layerSelector + '"></div>').show();

                    const comp = $compile($(directiveHtml))(newScope);
                    newScope.$apply();

                    $('#' + layerSelector).append(comp);
                    tr.addClass('shown');
                }
            });
        }

        function addEditEvent(table, containerSelector, directive, controller, callback) {
            $(containerSelector + ' tbody').off('click', 'td.info-edit');
            $(containerSelector + ' tbody').on('click', 'td.info-edit', function () {
                var tr = $(this).closest('tr');
                var row = table.row(tr);

                if (row.child.isShown()) {
                    row.child.hide();
                    tr.removeClass('shown');
                } else {
                    const newScope = $rootScope.$new();
                    newScope.data = $.extend(true, {}, row.data());
                    const directiveHtml = '<' + directive + ' class="' + directive + '" ng-controller="' + controller + '" ng-init="getProductCategories(\'' + newScope.data.category + '\')"></' + directive + '>';
                    const layerId = directive === 'suppliers-add-edit' ? newScope.data.id : newScope.data.idProduct + '-' + newScope.data.idSupplier + '-' + newScope.data.idCountry;
                    newScope.formAction = 'EDIT';
                    newScope.onUpdated = callback;
                    const layerSelector = 'edit-layer-' + layerId;
                    row.child('<div class="edit-tr" id="' + layerSelector + '"></div>').show();

                    const comp = $compile($(directiveHtml))(newScope);
                    newScope.$apply();

                    $('#' + layerSelector).append(comp);
                    tr.addClass('shown');
                }
            });
        }

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

            columnObj.visible = isColumnVisible(value);

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

            if(value === 'documents'){
                columnObj.className = 'show-documents';
            }

            return columnObj;
        }

        function isColumnVisible(value) {
            const notVisibleFields = [
                'idCountry',
                'idSupplier',
                'isPriceRecurring',
                'idProductType'
            ];

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

        function getSupplierProductsRenders() {
            return {
                payPeriod: payPeriodRender,
                unitCostPrice: priceRender,
                unitVatCost: priceRender,
                isAvailable: isAvailableRender,
                documents: documentsRender
            };

            function payPeriodRender(data) {
                return data !== '0' ? data : null;
            }

            function priceRender(data, type, row) {
                return parseInt(row.isPriceRecurring) === 1 ? data + ' / month' : data;
            }

            function isAvailableRender(data){
                return parseInt(data) === 1 ? 'yes' : 'no';
            }

            function documentsRender(data){
                let html = data.length > 0 ? '<div class="show-documents-icon"><span class="glyphicon glyphicon-plus"></span> Show</div>' : '-';

                return html;
            }
        }

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

            columnObj.visible = isColumnVisible(value);

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

            return columnObj;
        }

        function getSuppliersRenders() {
            return {
                sellsIn: suppliersSellsInRender
            };

            function suppliersSellsInRender(data) {
                return data ? data.replace(/,/g, '<br/>') : '-';
            }
        }
    }
})();
