(function() {
    'use strict';

    window.IDVE = window.IDVE || {};

    IDVE.History = {
        undoStack: [],
        redoStack: [],
        maxSize: 50,

        init: function() {
            this.undoStack = [];
            this.redoStack = [];
        },

        push: function() {
            if (!IDVE.state || !IDVE.state.tree) return;
            this.undoStack.push(this.clone(IDVE.state.tree));
            this.redoStack = [];
            if (this.undoStack.length > this.maxSize) {
                this.undoStack.shift();
            }
            this.updateButtons();
        },

        undo: function() {
            if (this.undoStack.length === 0) return;
            this.redoStack.push(this.clone(IDVE.state.tree));
            IDVE.state.tree = this.undoStack.pop();
            if (IDVE.Editor && IDVE.Editor.renderCanvas) {
                IDVE.Editor.renderCanvas();
            }
            IDVE.Editor.markDirty();
            this.updateButtons();
        },

        redo: function() {
            if (this.redoStack.length === 0) return;
            this.undoStack.push(this.clone(IDVE.state.tree));
            IDVE.state.tree = this.redoStack.pop();
            if (IDVE.Editor && IDVE.Editor.renderCanvas) {
                IDVE.Editor.renderCanvas();
            }
            IDVE.Editor.markDirty();
            this.updateButtons();
        },

        canUndo: function() { return this.undoStack.length > 0; },
        canRedo: function() { return this.redoStack.length > 0; },

        clear: function() {
            this.undoStack = [];
            this.redoStack = [];
            this.updateButtons();
        },

        clone: function(obj) {
            return JSON.parse(JSON.stringify(obj));
        },

        updateButtons: function() {
            var undoBtn = document.getElementById('idve-undo');
            var redoBtn = document.getElementById('idve-redo');
            if (undoBtn) undoBtn.disabled = !this.canUndo();
            if (redoBtn) redoBtn.disabled = !this.canRedo();
        }
    };
})();
