package speiger.src.coreengine.utils.collections.collection;

import java.util.Collection;
import java.util.List;

import speiger.src.collections.objects.lists.ObjectArrayList;
import speiger.src.collections.objects.utils.ObjectLists;

public class SaveState<T> {
	ObjectArrayList<T> entries = new ObjectArrayList<T>();
	ObjectArrayList<T> reverted = new ObjectArrayList<T>();
	boolean lock = false;
	
	public void push(T entry) {
		if(lock) return;
		entries.push(entry);
		reverted.clear();
	}
	
	@SuppressWarnings("deprecation")
	public void load(Collection<T> toLoad, boolean applied) {
		(applied ? entries : reverted).addAll(toLoad);
	}
	
	public T undo() {
		if(lock) throw new IllegalStateException("Save State Locked");
		if(entries.isEmpty()) { throw new IllegalStateException("No State Left"); }
		T value = entries.pop();
		reverted.push(value);
		return value;
	}
	
	public T redo() {
		if(lock) throw new IllegalStateException("Save State Locked");
		if(reverted.isEmpty()) { throw new IllegalStateException("Nothing to Undo"); }
		T value = reverted.pop();
		entries.push(value);
		return value;
	}
	
	public int index() {
		return entries.size();
	}
	
	public int max() {
		return entries.size() + reverted.size();
	}
	
	public List<T> getEntries() { return ObjectLists.unmodifiable(entries); }
	
	public List<T> getReverted() { return ObjectLists.unmodifiable(reverted); }
	
	public void clear() {
		reverted.clear();
		entries.clear();
	}
}