var ClearCache = (function () {

    var bindFunctions = function() {
        $(ClearCache.selector).on("click", function(){

            $.ajax({
                url: Routing.generate("cs_common_base_clear_cache"),
                method: "get",
                success: function () {
                    allowedModal();
                },
                error: function () {
                    deniedModal();
                }
            });
        });
    };

    var deniedModal = function() {
        var _modal = window.bootstrap.createModal().show(
            Translator.trans("common.clearCache.modal.denied.title"),
            Translator.trans("common.clearCache.modal.denied.message"),
            Translator.trans("common.clearCache.modal.denied.submit")
        );

        _modal.find('[data-btn-type="save"]').remove();
    };

    var allowedModal = function() {
        var _modal = window.bootstrap.createModal().show(
            Translator.trans("common.clearCache.modal.allowed.title"),
            Translator.trans("common.clearCache.modal.allowed.message"),
            Translator.trans("common.clearCache.modal.allowed.submit")
        );

        _modal.find('[data-btn-type="save"]').on('click', function (e) {
            $.ajax({
                url: Routing.generate("cs_common_base_clear_cache"),
                method: "post",
                beforeSend: function () {
                    _modal.find('[data-dismiss="modal"]').trigger('click');
                    $('.cs-module-spinner').show();
                },
                success: function () {
                    showToastrNotification("success", Translator.trans("common.clearCache.success"))
                },
                complete: function () {
                    $('.cs-module-spinner').hide();
                },
                error: function (response) {
                    if (response.status === 409) {
                        showToastrNotification("warning", Translator.trans("common.clearCache.unable"))
                    } else {
                        showToastrNotification("error", Translator.trans("common.clearCache.error"))
                    }
                }
            });
        });
    };

    return {
        init: function (options) {
            if (typeof options !== "undefined") {
                this.selector = options.selector;
            }
            bindFunctions();
        },
        selector: "#clear-cache"
    };
})();
