var WidgetQueue = Class.extend({
    init: function() {
        this.queue = [];
        this.listeners = [];
        this.addListeners();
    },
    enqueue: function(widget) {
        this.queue.push(widget);
    },
    dequeue: function() {
        return this.size() > 0 ? this.queue.shift() : null;
    },
    size: function() {
        return this.queue.length;
    },
    processQueue: function() {
        var widget = this.dequeue(),
            _self = this;
        
        if(CSTemplate.widgetsStorage.get(widget.uniqueId)) {
            widget.object = CSLayoutPageWidgets[widget.uuid];
            var selector = widget.getSelector(null, true);
            widget.renderObject(selector);
            setTimeout(function(){
                _self.dispatch(WidgetQueue.PROCESS_QUEUE_EVENT);
            }, 50);
        }
    },
    processRunTimeQueue: function() {
        var widget = this.dequeue();

        if(CSTemplate.widgetsStorage.get(widget.uniqueId)) {
            widget.getHtml(null, true);
        }
    },
    addListeners: function() {
        var _self = this;
        _self.listeners[WidgetQueue.PROCESS_QUEUE_EVENT] = new signals.Signal();
        _self.listeners[WidgetQueue.PROCESS_QUEUE_EVENT].add(function() {
            if(_self.size() > 0){
                _self.processQueue();
            } else {
                CSTemplate.allWidgetsLoaded = true;
                CSTemplate.actions.save(true);
                CSTemplate.actions.publish(true);
            }
        });

        _self.listeners[WidgetQueue.PROCESS_QUEUE_IN_RUNTIME_EVENT] = new signals.Signal();
        _self.listeners[WidgetQueue.PROCESS_QUEUE_IN_RUNTIME_EVENT].add(function() {
            if(_self.size() > 0){
                _self.processRunTimeQueue();
            }
        });
    },
    dispatch: function(event) {
        try{
            this.listeners[event].dispatch();
        } catch(exception){
            console.log(exception);
            console.error('This event isn\'t binded '+event);
        }

    }
});

WidgetQueue.PROCESS_QUEUE_EVENT = 'cswidget.process_queue';
WidgetQueue.PROCESS_QUEUE_IN_RUNTIME_EVENT = 'cswidget.process_queue_runtime';
