define(['../add_language_app', '../html/language_modals.html'], function(app, template){
    modalController.$inject = ['growl.service'];

    function modalController(growl){
        var modal = this;
        modal.code = '';
        modal.title = '';
        modal.saving = false;
        modal.mode = "add";
        modal.index = 0;
        modal.isError = false;
        modal.errorText = false;

        setTimeout(function(){
            angular.element("#app-container").on("modal-set-mode", function(event, context){
                modal.mode = context.mode;
                var langObj = context.langObj;
                modal.title = langObj.title;
                modal.code = langObj.code;
                modal.index = context.index;
                modal.isError = false;
                modal.saving = false;
            });

            angular.element("#app-container").on("language-success", function(){
                angular.element("#add-modal").modal("hide");
                modal.saving = false;
                growl.showSuccess(lmsg('panels.i18n.changes_ok'));
            });

            angular.element("#app-container").on("language-failure", function(event, context){
                modal.isError = true;
                modal.errorText = context.errorText;
                modal.saving = false;
            });
        }, 0);

        modal.send = function(code, title, index){
            modal.saving = true;
            var contextObj = {code: code, title: title, index: index};
            angular.element("#language-modals").trigger("modal-" + modal.mode, contextObj);
        };
    }

    app.directive('languageModals', function () {
        return {
            restrict: 'E',
            replace: true,
            bindToController: true,
            controllerAs: 'modal',
            templateUrl: template,
            controller: modalController
        }
    });
});