#include<stdlib.h>
#include "undo_controller.h"
#include "../operation/operation.h"



UndoController* _UndoController_Constructor(){
    UndoController* undo_controller = (UndoController*)malloc(sizeof(UndoController));
    undo_controller->operations = _Vector_Constructor(10);
    undo_controller->index=-1;
    return undo_controller;
}

void _UndoController_Destructor(UndoController* undo_controller){
    for(int i=0;i<_Vector_getLength(undo_controller->operations);i++)
        _Operation_Destructor((Operation*)(_Vector_getItem(undo_controller->operations,i)));
    _Vector_Destructor(undo_controller->operations);
    undo_controller->operations=NULL;
    free(undo_controller);
}

void _UndoController_recordOperation(UndoController* undo_controller,Operation* operation){
    for(int i = _Vector_getLength(undo_controller->operations)-1;i>undo_controller->index;i--){
        _Operation_Destructor((Operation*)(_Vector_getItem(undo_controller->operations,i)));
        _Vector_delete(undo_controller->operations,i);
    }
    _Vector_add(undo_controller->operations,operation);
    undo_controller->index+=1;
}

int _UndoController_undo(UndoController* undo_controller){
    if(undo_controller->index<0)
        return 1;
    _Operation_Undo((Operation*)(_Vector_getItem(undo_controller->operations,undo_controller->index)));
    undo_controller->index--;
    return 0;
}

int _UndoController_redo(UndoController* undo_controller){
    if(undo_controller->index + 1 >= _Vector_getLength(undo_controller->operations))
        return 1;
    undo_controller->index++;
    _Operation_Do((Operation*)(_Vector_getItem(undo_controller->operations,undo_controller->index)));
    return 0;
}