package jrummikub.control;

import static jrummikub.model.StoneColor.*;
import static org.junit.Assert.*;

import java.awt.Color;
import java.io.File;
import java.io.IOException;

import jrummikub.model.GameSettings;
import jrummikub.model.GameState;
import jrummikub.model.IRoundState;
import jrummikub.model.PlayerSettings;
import jrummikub.model.Position;
import jrummikub.model.RoundState;
import jrummikub.model.Stone;
import jrummikub.model.StoneSet;
import jrummikub.util.IListener3;
import jrummikub.view.MockView;

import org.junit.Test;

/** */
public class SaveControlTest {
	/**
	 * @throws IOException
	 *           if input cannot be saved/loaded
	 */
	@Test
	public void testSaveLoad() throws IOException {
		GameSettings settings = new GameSettings();
		settings.getPlayerList().add(new PlayerSettings("Matze", Color.GREEN));
		settings.getPlayerList().add(new PlayerSettings("Ida", Color.PINK));

		GameState gameState = new GameState();
		RoundState roundState = new RoundState(settings, null);

		Stone stone1 = new Stone(1, RED);
		Stone stone2 = new Stone(5, RED);
		Stone stone3 = new Stone(2, RED);

		roundState.getTable().drop(new StoneSet(stone1), new Position(0, 0));
		roundState.getActivePlayer().getHand().drop(stone2, new Position(0, 0));
		roundState.getActivePlayer().getHand().drop(stone3, new Position(0, 0));

		MockView view = new MockView();
		SaveControl saveControl = new SaveControl(view);
		saveControl.setGameSettings(settings);
		saveControl.setGameState(gameState);
		saveControl.setRoundState(roundState);

		File file = File.createTempFile("testSave", ".rum");

		view.saveEvent.emit(file);

		saveControl.getLoadEvent().add(
				new IListener3<GameSettings, GameState, IRoundState>() {
					@Override
					public void handle(GameSettings settings, GameState gameState,
							IRoundState roundState) {
						assertEquals(2, settings.getPlayerList().size());
						assertEquals(1, roundState.getTable().getSize());
						assertEquals(2, roundState.getActivePlayer().getHand().getSize());
					}
				});

		view.loadEvent.emit();
		view.getQuitWarningPanel().quitEvent.emit();
		
		view.loadFileEvent.emit(file);
		file.delete();
	}
}
