package rules;

import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;

import csp.CSPInstance;
import csp.CSPSolution;

import scg.Claim;
import scg.ParseException;
import scg.net.PlayerSpec;
import scg.net.admin.RemotePlayerProxy;
import scg.protocolInterpreter.StrengtheningProtocolInterpreter;

public class TestStrengthenProtocolInterpreter {

	private static final int INITIAL_REPUTATION = 100;
	private static final int TIMEOUT = 60;
	private static final double DELTA = 0.008;
	private static final double DELTA_BIG = 0.8;

	private RemotePlayerProxy alice;
	private RemotePlayerProxy bob;

	@Before
	public void initTest() {
		alice = new RemotePlayerProxy(new PlayerSpec("alice", "localhost", -1), TIMEOUT,
				INITIAL_REPUTATION);
		bob = new RemotePlayerProxy(new PlayerSpec("bob", "localhost", -1), TIMEOUT,
				INITIAL_REPUTATION);
	}

	@Test
	public void test1() throws ParseException, csp.ParseException {
		Claim originalClaim = Claim
				.parse("csp.CSPInstanceSet {{ (12 22) }} scg.protocol.PositiveSecret {{ }} 0.444444 0.8");
		Claim strengthenedClaim = Claim
				.parse("csp.CSPInstanceSet {{ (12 22) }} scg.protocol.PositiveSecret {{ }} 0.454444 0.8");
		StrengtheningProtocolInterpreter spi = new StrengtheningProtocolInterpreter(alice, bob,
				strengthenedClaim, originalClaim);

		Assert.assertFalse(spi.isComplete());

		spi.setInstance(CSPInstance.parse("x1 x2 x3 (12 {1} x1 x2 x3)"));
		spi.proceed();
		Assert.assertFalse(spi.isComplete());

		spi.setSolution(CSPSolution.parse("[(x1->true) (x2->true) (x3->false)]"));
		spi.proceed();

		spi.setSolution(CSPSolution.parse("[(x1->true) (x2->true) (x3->true)]"));
		spi.proceed();
		spi.proceed();
		Assert.assertEquals(-1d, spi.getResult()); // Bob Wins
		Assert.assertEquals(INITIAL_REPUTATION + DELTA, bob.getReputation());
		Assert.assertEquals(INITIAL_REPUTATION - DELTA, alice.getReputation());
	}

	@Test
	public void test2() throws ParseException, csp.ParseException {
		Claim originalClaim = Claim
		.parse("csp.CSPInstanceSet {{ (12 22) }} scg.protocol.NegativeSecret {{ }} 0.444444 0.8");
		Claim strengthenedClaim = Claim
		.parse("csp.CSPInstanceSet {{ (12 22) }} scg.protocol.NegativeSecret {{ }} 0.422222 0.8");
		StrengtheningProtocolInterpreter spi = new StrengtheningProtocolInterpreter(alice, bob,
				strengthenedClaim, originalClaim);
		
		Assert.assertFalse(spi.isComplete());
		
		spi.setInstance(CSPInstance.parse("x1 x2 x3 (12 {1} x1 x2 x3)"));
		spi.proceed();
		Assert.assertFalse(spi.isComplete());
		
		spi.setSolution(CSPSolution.parse("[(x1->true) (x2->true) (x3->false)]"));
		spi.proceed();
		
		spi.setSolution(CSPSolution.parse("[(x1->true) (x2->true) (x3->true)]"));
		spi.proceed();
		spi.proceed();
		Assert.assertTrue(spi.isComplete());
		Assert.assertEquals(1d, spi.getResult()); // Alice Wins
		Assert.assertEquals(INITIAL_REPUTATION + DELTA_BIG, alice.getReputation());
		Assert.assertEquals(INITIAL_REPUTATION - DELTA_BIG, bob.getReputation());
	}
}
