var AutoSave = (function() {
    var isGoingToDraft = false;
    var intervalTime   = 30000;

    var init = function(formId, key) {
        if (!ComitiumUtils.getURLParameter("draft")) {
            $('[data-action="cancel-form"]').on("click", function () {
                discard(formId, key);
            });

            $(window).on("beforeunload", function (e) {
                if (!isGoingToDraft) {
                    discard(formId, key);
                }
            });
        } else {
            showOnDraftPageMessage(key);
        }

        $('form[name="'+formId+'"]')
            .attr("method", "post")
            .on("submit", function () {
            removeStorage(key);
        });

        checkDraft(
            formId,
            key,
            initInterval
        );
    };

    var initInterval = function (formId, key, avoidFirstExecution) {
        if (!avoidFirstExecution) {
            execute(formId, key);
        }

        setInterval(function(){
            execute(formId, key);
        }, intervalTime);
    };

    var checkDraft = function(formId, key, allowedCallback) {
        if (!ComitiumUtils.getURLParameter("draft")) {
            $.ajax({
                url: Routing.generate("cs_core_check_auto_save"),
                data: {
                    key : key,
                    formId: formId
                },
                method: "post",
                success: function(response){
                    if (response.allowed) {
                        allowedCallback.call(this, formId, key);
                    } else {
                        var draftUrl  = ComitiumUtils.addURLParameter(response.referer, "draft", 1);
                        showDraftMessage(draftUrl, formId, key);
                    }
                }
            })
        }
    };

    var execute = function(formId, key) {

        var serializedData = $('form[name="'+formId+'"]').serialize();

        //Save data on local storage
        setStorage(key, serializedData);

        $.ajax({
            url: Routing.generate("cs_core_auto_save"),
            data: {
                formData: serializedData,
                key : key,
                formId: formId,
                referer: window.location.href
            },
            method: "post",
            error: function() {
                showToastrNotification("error", Translator.trans("cs_core.auto_save.save_error"));
            }
        })
    };

    var discard = function(formId, key) {
        removeStorage(key);
        hideMessage();
        $.ajax({
            url: Routing.generate("cs_core_auto_save_discard"),
            data: {
                key : key,
                formId: formId
            },
            method: "post"
        })
    };

    var removeStorage = function(key) {
        if (typeof(Storage) !== "undefined") {
            localStorage.removeItem(key);
        }
    };

    var setStorage = function(key, data) {
        if (typeof(Storage) !== "undefined") {
            localStorage.setItem(key, data);
        }
    };

    var showDraftMessage = function(draftUrl, formId, key) {
        var message = Translator.trans("cs_core.auto_save.draft_message", {
            draftUrl: draftUrl,
            formId: formId,
            key: key
        });

        $("body").append(message);
    };

    var showOnDraftPageMessage = function(key) {
        var messageKey = /edit/.test(window.location.href)  ?
            "cs_core.auto_save.on_draft_page_message_edit":
            "cs_core.auto_save.on_draft_page_message_create";

        var message = Translator.trans(messageKey, {
            discardUrl: Routing.generate("cs_core_auto_save_discard", {key: key})
        });
        console.log(message);
        $("body").append(message);
    };

    var hideMessage = function () {
        $(".draft-info").fadeOut();
    };

    return {
        init: function(formId, key) {
            init(formId, key);
        },
        execute: function(formId, key) {
            execute(formId, key);
        },
        discard: function(formId, key, restart) {
            discard(formId, key);

            if (restart) {
                initInterval(formId, key, true);
            }
        },
        hideMessage: function() {
            hideMessage();
        },
        setGoToDraft: function(el) {
            isGoingToDraft = true;
            window.location.href = el.attr("href");
        }
    };
})();
