//
//  PeggingPanel.java
//  cribbage
//
//  Created by Nathan Haug on Wed Apr 28 2004.
//  Copyright (c) 2004 __MyCompanyName__. All rights reserved.
//

import javax.swing.*;
import java.awt.*;

public class PeggingPanel extends JPanel {

	private ImageIcon emptyPeg;
	private ImageIcon filledPeg;
	private JLabel pegHoles[];
	private BoardPanel board;
	
	private int pegLoc1;
	private int pegLoc2;
	private int color;
	
	public PeggingPanel (int color, BoardPanel board) {
		super();
		
		this.color = color;
		this.board = board;
		emptyPeg = new ImageIcon("./images/pegEmpty"+color+".gif");
		filledPeg = new ImageIcon("./images/peg"+color+".gif");
		
		
		// These two variable represent the players score
		// The higher one is all that matters, reflecting the current score
		pegLoc1 = 0;
		pegLoc2 = 0;
	
		// Define our layout
		BoxLayout columnLayout = new BoxLayout(this,BoxLayout.Y_AXIS);
		this.setLayout(columnLayout);
		
		// Make the holes
		pegHoles = new JLabel[120];
		for (int i=0; i<pegHoles.length; i++)
			pegHoles[i] = new JLabel(emptyPeg);
			
		// Put the holes into the layout
		for (int i=0; i<pegHoles.length; i++)
			this.add(pegHoles[i]);
			
		this.setVisible(true);
	}
	
	public void addScore (int score) {
		// Adjustst the pegs on the board.
		// The subtractions from 120 let the board start at the bottom
		// rather than the top.
		if (score > 0) {
			if (pegLoc1 == 0) {
				pegHoles[120-score].setIcon(filledPeg);
				pegLoc1 = score;
			}
			else if (pegLoc2 ==0) {
				pegLoc2 = score+pegLoc1;
				pegHoles[120-pegLoc2].setIcon(filledPeg);
			}
			else if (pegLoc2 > pegLoc1) {
				pegHoles[120-pegLoc1].setIcon(emptyPeg);
				pegLoc1 = score + pegLoc2;
				if (pegLoc1 > 120)
					board.setWinPeg(color);
				else
					pegHoles[120-pegLoc1].setIcon(filledPeg);
			}
			else if (pegLoc1 > pegLoc2) {
				pegHoles[120-pegLoc2].setIcon(emptyPeg);
				pegLoc2 = score + pegLoc1;
				if (pegLoc2 > 120)
					board.setWinPeg(color);
				else
					pegHoles[120-pegLoc2].setIcon(filledPeg);		
			}
		}
	}
}
