(function () {
    global.dashModule.service('dataTableHelper', ['$translate', '$', dataTableHelper]);

    function dataTableHelper($translate, $) {
        const language = {
            lengthMenu: 'Display _MENU_ records per page',
            zeroRecords: 'Nothing found - sorry',
            info: 'Showing page _PAGE_ of _PAGES_',
            infoEmpty: 'No records available',
            infoFiltered: '(filtered from _MAX_ total records)'
        };

        return {
            generateColumns,
            showTable,
            setDataTableLanguage
        };

        function setDataTableLanguage() {
            const translationPath = 'dataTable.';
            const dataTableKeys = ['dataTable.lengthMenu', 'dataTable.zeroRecords', 'dataTable.info', 'dataTable.infoEmpty', 'dataTable.infoFiltered'];
            $translate(dataTableKeys).then(translations => {
                Object.keys(language).forEach(key => {
                    language[key] = translations[translationPath + key];
                });
                redrawTables();
            });
        }

        /**
         * Genereates the columns to shod the data table from source data
         * @param  {[type]}   keys                               resource keys (headers) from witch the datable is created
         * @param  {[type]}   translationPath                    path to module translate
         * @param  {Function} callback                           callback function to be triggered after translation
         * @param  {[type]}   callbackParams                     extra parameters for callback function (includes extra options for the table)
         * @param  {[type]}   [customFormatColumns=formatColumn] custom function for formating the columns, if none is given the default one is used form the helper
         * @return {[type]}                                      returns promies with datable created object as response
         */
        function generateColumns(keys, translationPath, callback, callbackParams, customFormatColumns = formatColumn) {
            const keysArray = [];
            keys.forEach(value => {
                keysArray.push(translationPath + value);
            });

            return $translate(keysArray).then((translations => {
                return setColumns(translations);
            }), translationIds => {
                return setColumns(translationIds);
            });

            function setColumns(translations) {
                const columns = [];
                if (typeof callbackParams.hasDetails !== 'undefined') {
                    columns.push({
                        className: 'info-control',
                        orderable: false,
                        data: null,
                        defaultContent: '',
                        title: '<div class="data-tabel-info-icon glyphicon glyphicon-info-sign"></div>'
                    });
                }

                if (typeof callbackParams.hasEdit !== 'undefined') {
                    columns.push({
                        className: 'info-edit',
                        orderable: false,
                        data: null,
                        defaultContent: '<div class="data-table-edit glyphicon glyphicon-pencil"></div>',
                        width: '20px',
                        title: '<div class="data-table-edit-title glyphicon glyphicon-pencil"></div>'
                    });
                }

                keys.forEach((value) => {
                    columns.push(customFormatColumns(value, translations, translationPath));
                });

                return callback(columns, callbackParams);
            }
        }

        function formatColumn(value, translations, translationPath) {
            return {
                data: value,
                title: translations[translationPath + value]
            };
        }

        /**
         * Append datatable to the dom and returns the created object
         * @param  {[type]} columns generated columns for witch the table should be rendered
         * @param  {[type]} params  extra parameters for the table (ajax urle, extra table options)
         * @return {[type]}         data table object that has been rendered to the doom
         */
        function showTable(columns, params) {
            const tableOptions = {
                ajax: {
                    url: params.url,
                    method: 'POST',
                    data: params.data
                },
                language,
                columns,
                responsive: true,
                autoWidth: false,
                iDisplayLength: 50
            };

            if (typeof params.extraTableOptions !== 'undefined') {
                $.extend(tableOptions, params.extraTableOptions);
            }

            if ($.fn.dataTable.fnIsDataTable($(params.selector))) {
                tableOptions.destroy = true;
            }

            return $(params.selector).DataTable(tableOptions);
        }

        function redrawTables() {
            $('table').each(function () {
                if ($.fn.dataTable.fnIsDataTable(this)) {
                    $(this).DataTable({
                        destroy: true,
                        language
                    });
                }
            });
        }
    }
})();
