(function () {
    global.dashModule.config(['$translateProvider', function ($translateProvider) {
        $translateProvider.useUrlLoader('translate/api/getTranslation');
        const lang = hasLanguageInStorage() ? localStorage.lang : 'en';
        $translateProvider.preferredLanguage(lang);
        $translateProvider.useSanitizeValueStrategy('escape');
    }]);

    global.dashModule
        .controller('translateCtrl', ['$translate', '$scope', 'dataTableHelper', translateCtrl])
        .directive('translateMain', [translateMain]);

    function translateMain() {
        return {
            restrict: 'E',
            templateUrl: 'translate/html/languagesTemplate'
        };
    }

    function translateCtrl($translate, $scope, dataTableHelper) {
        $scope.lang = hasLanguageInStorage() ? localStorage.lang : 'en';
        $scope.changeLanguage = changeLanguage;

        function changeLanguage() {
            $translate.use($scope.lang).then(() => {
                setLanguageInStorage($scope.lang);
                dataTableHelper.setDataTableLanguage();
            });
        }
    }

    function hasLanguageInStorage() {
        return typeof Storage !== 'undefined' && typeof localStorage.lang !== 'undefined';
    }

    function setLanguageInStorage(lang) {
        if (typeof Storage !== 'undefined') {
            localStorage.setItem('lang', lang);
        }
    }

})();
