var BlockContent = (function() {

    var checkOwnerInterval;

    var init = function(entityClass, entityId, callBack) {
        window.entityClass = entityClass;
        window.entityId = entityId;
        blockContent(entityClass, entityId, callBack);
        bindEvents(entityClass, entityId, callBack);
    };

    var bindEvents = function(entityClass, entityId, callBack) {

        $('[data-action="cancel-form"]').on('click', function(e, param) {
            if (typeof param === "undefined" || param.unblokContent === true) {
                unBlockContent(entityClass, entityId);
            }

            window.location.href = $(this).attr("href");
        });

        $( window ).on("beforeunload", function() {

            var _currentLocation = window.location.href;
            unBlockContent(entityClass, entityId);
            setTimeout(function(){
                var _newLocation = window.location.href;

                if( _currentLocation === _newLocation) {
                    // Block again the content because user is in the same page yet
                    // This occurs if click on stay on this page after some form change
                    blockContent(entityClass, entityId);
                }
            }, 10000);
        });
    };

    var checkIfIamOwner = function(entityClass, entityId) {

        clearInterval(checkOwnerInterval);

        checkOwnerInterval = setInterval(function(){
            isBlocked(entityClass, entityId, function(response){
                if (response !== null) {
                    if (response.blockedBy === 1) {
                        clearInterval(checkOwnerInterval);
                        displayMissOwnerMessage(response);
                    }
                }
            });
        }, 10000);
    };

    var blockContent = function(entityClass, entityId, callBack) {

        if (typeof callBack !== "function") {
            callBack = function(response){
                var tabs = 0;
                if (typeof(Storage) !== "undefined") {
                    tabs = localStorage.getItem("tabs");
                }

                if (response.success === false &&  ( (response.blockedBy === 1) || (response.blockedBy === 2 && tabs > 1) )) {
                    displayBlockMessage(response, entityClass, entityId, callBack);
                } else {
                    checkIfIamOwner(entityClass, entityId);
                }
            };
        }

        send("cs_core_block_content_block_content", {entityClass:entityClass, id:entityId }, callBack, { async:true });
    };

    var getControlForBlockContent = function(entityClass, entityId, callBack) {
        send("cs_core_block_content_get_control", {entityClass:entityClass, id:entityId }, callBack, { async:true });
    };

    var unBlockContent = function(entityClass, entityId, callBack) {
        clearInterval(checkOwnerInterval);
        entityClass = entityClass||window.entityClass;
        entityId    = entityId||window.entityId;

        send("cs_core_block_content_unblock_content", {entityClass:entityClass, id:entityId }, callBack, { async:true });
    };

    var isBlocked = function(entityClass, entityId, callBack) {
        send("cs_core_block_content_is_blocked", {entityClass:entityClass, id:entityId }, callBack, { async:true });
    };

    var send = function(url, data, callBack, options){
        $.ajax({
            url: Routing.generate(url),
            async: options.async,
            dataType: "json",
            data: data,
            complete: function(jqXHR){
                if (typeof callBack === "function") {
                    callBack.call(this, jqXHR.responseJSON);
                }
            }
        });
    };

    var bootstrapModal = {
        createModal: function() {
            return {
                struct: '<div class="modal"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal"><span>&times;</span><span class="sr-only">Close</span></button><h4 class="modal-title"></h4></div><div class="modal-body"></div><div class="modal-footer"><button type="button" class="btn defaultBtn" data-dismiss="modal" data-btn-type="cancel"></button><button type="button"class="btn mainBtn" data-btn-type="save"></button></div></div></div></div>',
                show: function (header, body, button, hiddenAccept, modalOptions) {
                    var modal = $(_bootstrapModal.struct);
                    modal.find('h4').html(header);
                    modal.find('.modal-body').html(body);
                    modal.find('[data-btn-type="save"]').html(button);
                    modal.find('[data-btn-type="cancel"]').html(Translator.trans("cs_core.action.cancel.default"));

                    if (typeof modalOptions === "object") {
                        modal.filter('.modal').modal(modalOptions);
                    } else {
                        modal.filter('.modal').modal('show');
                    }


                    if (hiddenAccept) {
                        modal.find('[data-btn-type="save"]').remove();
                    }

                    return modal;
                },
                hide: function () {
                    var modal = $(_bootstrapModal.struct);
                    $('body').filter('.modal').modal('hide');
                }
            };
        }
    };

    var _bootstrapModal = bootstrapModal.createModal();

    var displayBlockMessage = function(response, entityClass, entityId, callBack) {

        var choice = response.data.allowUnlockContent === false && response.blockedBy != 2 ? 3 : response.blockedBy;

        var _modal = _bootstrapModal.show(
            Translator.trans('blockContent.modalBlock.title'),
            Translator.transChoice('blockContent.modalBlock.message', choice, {'user': response.data.user.fullName, 'date': response.data.lockedDate }),
            Translator.trans('blockContent.modalBlock.backToList'),
            false,
            { backdrop: "static", keyboard: false, show: true }
        );

        _modal.find('[data-btn-type="cancel"], .close').remove();
        _modal.find('[data-btn-type="save"]').toggleClass('mainBtn defaultBtn');

        if (response.data.allowUnlockContent === true || response.blockedBy === 2) {
            var getControlButton = $('<button></button>', {
                'class': 'btn mainBtn',
                'id': 'get-control-action',
                'text': Translator.transChoice('blockContent.modalBlock.getControl', response.blockedBy)
            });

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

            _modal.find('#get-control-action').on('click', function (e) {

                if (response.blockedBy == 1) {
                    getControlForBlockContent(entityClass, entityId, callBack);
                }

                checkIfIamOwner(entityClass, entityId);

                _modal.modal("hide");
            });
        }

        _modal.find('[data-btn-type="save"]').on('click', function () {
            triggerCancel(false);
        });
    };

    var displayMissOwnerMessage = function(response) {

        var _modal = _bootstrapModal.show(
            Translator.trans('blockContent.modalMiss.title'),
            Translator.transChoice('blockContent.modalMiss.message', response.blockedBy, {'user': response.data.user.fullName, 'date': response.data.lockedDateFormat }),
            Translator.trans('blockContent.modalMiss.submit'),
            false,
            { backdrop: "static", keyboard: false, show: true }
        );

        _modal.find('[data-btn-type="cancel"], .close').remove();

        _modal.find('[data-btn-type="save"]').on('click', function () {
            triggerCancel(false);
        });
    };

    var saveAsClone = function() {

        var form   = $("form");
        var url    = ComitiumUtils.addURLParameter(window.location.pathname, "saveAsClone", 1);
        var data   = form.serialize();
        var method = form.attr("method");

        $.ajax({
            url: url,
            data: data,
            method: method,
            success: function(){
                triggerCancel(false);
            },
            error: function() {
                showToastrNotification('error', Translator.trans("cs_core.messages.generic_error"));
            }
        });
    };

    var triggerCancel = function(unblock) {
        $('[data-action="cancel-form"]').trigger("click", {unblokContent: unblock});
    };

    return {
        init: function(entityClass, entityId, callBack) {
            console.warn("TODO BlockContent.js action init");
            // init(entityClass, entityId, callBack);
        },
        isBlocked: function(entityClass, entityId, callBack) {
            console.warn("TODO BlockContent.js action isBlocked");
            // isBlocked(entityClass, entityId, callBack);
        },
        blockContent: function(entityClass, entityId, callBack) {
            console.warn("TODO BlockContent.js action blockContent");
            // blockContent(entityClass, entityId, callBack);
        },
        unBlockContent: function(entityClass, entityId, callBack) {
            console.warn("TODO BlockContent.js action unBlockContent");
            // unBlockContent(entityClass, entityId, callBack);
        }
    };
})();
