package edu.gettysburg.pigapp;

import android.util.Log;
import cs1.android.*;

import java.util.Random;


public class PigApp extends AndroidApp
{
	private Random random = new Random();
	private int myScore;     // player's score
	private int halScore;    // computer's score
	private boolean myTurn;  // indicates player's turn
	private int turnTotal;   // current turn total
	private int roll;        // latest die roll
	
	/**
	 * Initializes the game state.
	 */
	public PigApp()
	{
		myScore = 0;
		halScore = 0;	
		turnTotal = 0;
		roll = 1;
		myTurn = true;
	}
	
	
	/**
	 * Draws the current state of the board.
	 */
	private void drawBoard()
	{
		Log.i("drawBoard", "myTurn: " + myTurn);
		Log.i("drawBoard", "myScore: " + myScore);
		Log.i("drawBoard", "halScore: " + halScore);
		Log.i("drawBoard", "roll: " + roll);
		Log.i("drawBoard", "turnTotal: " + turnTotal);
	}
	
	/**
	 * Returns a random integer in [1..6].
	 * @return  random integer in [1..6]
	 */
	private int rollDie()
	{
		// draw the die roll
//		canvas.drawImage(360, 160, "die5roll.png");
//		canvas.sleep(0.2);
				
		roll = random.nextInt(6) + 1;
		if (roll == 1) {
			turnTotal = 0;
			myTurn = !myTurn;
		}
		else
			turnTotal += roll;
		return roll;
	}
	
	private void hold() {
		if (myTurn)
			myScore += turnTotal;
		else
			halScore += turnTotal;
		turnTotal = 0;
		myTurn = !myTurn;
	}

	/**
	 * Runs the game. (Required method by the framework).
	 */
	public void run() 
	{	
		drawBoard();
		while (myScore < 100 && halScore < 100) {
			// player's turn
			if (myTurn == true) {
				if (turnTotal >= 20 || turnTotal + myScore >= 100) // require first roll, tap on player score --> hold
					hold();
				else // tap elsewhere --> roll
					rollDie();
			}
			else {  // HAL's turn
				canvas.sleep(1);	
				if (rollDie() != 1) {
					boolean isHolding = false;
					if (halScore + turnTotal >= 100)
						isHolding = true;
					else if (halScore >= 71 || myScore >= 71)
						isHolding = false;
					else
						isHolding = turnTotal >= 21 + (int) Math.round((myScore - halScore) / 8.0);
					if (isHolding)
						hold();
				}
			}
			
			drawBoard(); 
		}
		myTurn = !myTurn;
		drawBoard();
		canvas.drawText(240, 90, (myScore >= 100) ? "You Win!" : "You lose.", 28, "cyan");
	}
}
