/**
 * Mesaje aplicatie pot fi transmise:
 *  - actiuni
 *  - administrare
 *
 */
(function(){

    var TYPE_ACTION = 0;
    var TYPE_ALERT = 1;
    var TYPE_PERMANENT = 2;

    var shownMessages = [];

    /**
     * Afisare mesaje pe interfata
     * @param messages
     */
    function showMessages(messages){
        console.log("showMessages", messages);

        if( messages && messages.length == 0){
            return;
        }

        var count = 0;
        var cntAction=0;
        shownMessages = [];

        jQuery(messages).each(function (i, m) {
            count++;

            var type = "";
            if (m.type == TYPE_ACTION) {
                type = "action-message";
                cntAction++;
            } else if(m.type == TYPE_ALERT)  {
                type = "alert-message";
            } else if(m.type == TYPE_PERMANENT)  {
                type = "permanent-message";
            }

            var html = "<div class='message "+type+"'>" + (m.message ? m.message : m) + "</div>";

            jQuery(MessagesConfig.messagesWrapper).append(html);

            shownMessages.push(m);
        });



        if( count > 0){
            jQuery(MessagesConfig.messagesWrapper).addClass("visible").removeClass("hidden");

            if( cntAction > 0){
                setTimeout(function(){
                    jQuery(MessagesConfig.messagesWrapper).removeClass("visible").addClass("hidden");
                }, 10*1000);    //10 sec
            }

        }else{
            jQuery(MessagesConfig.messagesWrapper).removeClass("visible").addClass("hidden");
        }
    }

    /**
     * Load messages
     */
    function getMessagesForCurrentApp( successCallback, errorCallback) {
        jQuery.ajax({
            type: "GET",
            url: MessagesConfig.messagesService + "?action=get-messages&application="+MessagesConfig.appName+"&username="+MessagesConfig.currentUser,
            dataType: "text",

            success: function (responseText) {
                var responseMessage = getResponseMesg(responseText);
                try {
                    var jsonObject = jQuery.parseJSON(responseMessage);
                    successCallback(jsonObject);
                }catch(e){
                    if(console){
                        console.error("Eroarea procesare mesaj, response: " + responseText);
                    }
                }
            },

            error: function(error){
                errorCallback(error);
            }
        });
    }

    function setMessageAsRead(){
        var messagesParameter = "";
        jQuery(shownMessages).each(function (i, m) {
            if(m.id){
                messagesParameter += "&id="+m.id;
            }
        });

        jQuery.ajax({
            type: "GET",
            url: MessagesConfig.messagesService + "?action=set-message-as-read" + messagesParameter + "&username=" + MessagesConfig.currentUser,
            dataType: "text",
            success: function (responseText) {
                var responseMessage = getResponseMesg(responseText);
                if( console) {
                    console.log("set-message-as-read response", responseMessage);
                }
            }
        });
    }

    function hideAlertMessage(){
        jQuery(MessagesConfig.messagesWrapper).hide();
    }


    //
    // Check config
    //
    if (typeof MessagesConfig === 'undefined') {
        //default config
        MessagesConfig = {
            messagesWrapper : ".messagesWrapper",
            messagesService: "/emid-admin/emid-admin.default",
            appName: "todo",
            currentUser : "todo",
            messages:[]
        };
    }

    jQuery(document).ready(function(){
        //
        // init
        //
        //jQuery(MessagesConfig.messagesWrapper + " .close")
        jQuery(MessagesConfig.messagesWrapper)
            .attr("title", "Click pentru a inchide mesajul")
            .click(function(){
                hideAlertMessage();
                setMessageAsRead();
            });

        showMessages(MessagesConfig.messages);

        getMessagesForCurrentApp(
            function(messages){
                showMessages(messages);
            }, function(error){

            }
        );
    });
})();