package edu.dartmouth.cs.kalah;

/**
 * KalahViewGraphical.java
 *
 * @author Scot Drysdale on 7/2011
 *
 * A graphical implementation of the "view" part of a model-view-controller 
 *   version of a Kalah program.  (See Kalah.java for history.)
 * See KalahView interface for comments on the required methods.
 */

import javax.swing.*;
import edu.dartmouth.cs.kalah.KalahGame;

public class KalahViewGraphical implements KalahView {

  private final int DEFAULT_FRAME_WIDTH = 620;
  private final int DEFAULT_FRAME_HEIGHT = 150;
	private KalahFrame frame;					// Holds the graphical representation
	
	public KalahViewGraphical (){
			frame = new KalahFrame();
			frame.setTitle("Kalah");
  		frame.setVisible(true);
		
      frame.setSize(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HEIGHT);
      
  		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	}
  
	@Override
	public void display (KalahGame state) {
		frame.display(state);
  }
	
	@Override
	public int getUserMove(KalahGame state) {
		int [] board = state.getBoard();
	
		frame.moveChosen = -1;   // Set to an invalid value

		while (frame.moveChosen == -1) {
			// Busy wait for button to be pushed.  
			while (frame.moveChosen == -1) {
				CSJavaLib.pause(100);           // Wait 100 msec before checking again
		}
			// Verify that the move is valid
			if ((frame.moveChosen < 1 + state.getPlayerNum()*KalahGame.HALFPITS) || 
					(frame.moveChosen > KalahGame.SIDEPITS + state.getPlayerNum()*KalahGame.HALFPITS) || 
					(board[frame.moveChosen] == 0)) 
				frame.moveChosen = -1;
    }   
    return frame.moveChosen;
	}
	
	@Override
  public String getAnswer(String question) {
		String inputValue = JOptionPane.showInputDialog(question);
		return inputValue;
  }
  
	@Override
  public int getIntAnswer(String question) {
  	boolean valid = false;  // Has a valid number been read?
  	int answer = 0;         // The answer to the question
  	
  	while(!valid) {
  		// Asks user for a number
  		String inputValue = JOptionPane.showInputDialog(question);
  		try {
        answer = Integer.parseInt(inputValue);
        valid = true;   // If got to here we have a valid integer
  		}
  		catch(NumberFormatException ex) {
  			reportToUser("\"" + inputValue + "\" is not a valid integer");
  			valid = false;
  		}
  	}
		return answer;
  }
  
  @Override
  public void reportToUser(String message) {
  // Reports something to the user
  	JOptionPane.showMessageDialog(null, message,
  			message, JOptionPane.INFORMATION_MESSAGE);
  }

	@Override
	public void reportMove(int bestMove, String name) {
//		JOptionPane.showInternalMessageDialog(southFrame, (name + " empties pit " + bestMove),
//				(name + " empties pit " + bestMove), JOptionPane.INFORMATION_MESSAGE);
		CSJavaLib.pause(500);
	}
}
