package sudoku.structure;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

//TODO: doc
public class StateManager {

	private final Stack<Map<Cell, Integer>> states;
	private final MultiDoku doku;

	public StateManager(MultiDoku doku) {
		this.states = new Stack<>();
		this.doku = doku;
	}

	public Map<Cell, Integer> pushState() {
		states.add(saveState());
		return states.getLast();
	}

	public void popState() {
		assert (states.size() > 0);
		restoreState(states.pop());
	}

	public Map<Cell, Integer> popAndGetState() {
		assert (states.size() > 0);
		var currentState = saveState();
		restoreState(states.pop());
		return currentState;
	}

	private void restoreState(Map<Cell, Integer> state) {
		for (var entry : state.entrySet()) {
			entry.getKey().setSymbolIndex(entry.getValue());
		}
	}

	private Map<Cell, Integer> saveState() {
		Map<Cell, Integer> state = new HashMap<>();
		for (Cell cell : this.doku.getCells()) {
			state.put(cell, cell.getSymbolIndex());
		}
		return state;
	}

}
