/**
 * 
 */
package com.example.tictactoe;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import org.apache.commons.*;



/**
 * the button !!!!!
 * @author alexis
 * 
 */
public class ThreeStateButton extends Button implements OnClickListener{

	/**
	 * 
	 */
	//0 = nothing 1=player1 2=player2 else=corrupted
	State state;		//modifier par martin, remplacer byte par un enum
	MainActivity game;
	

	/**
	 * @param context from witch activity
	 */
	public ThreeStateButton (Context context) {
	    super(context);
	    init(context);
	}

	/**
	 * @param context from witch activity
	 * @param attrs
	 */
	public ThreeStateButton (Context context, AttributeSet attrs) {
	    super(context, attrs);
	    init(context);
	}

	/**
	 * @param context from witch activity
	 * @param attrs
	 * @param defStyle
	 */
	public ThreeStateButton (Context context, AttributeSet attrs, int defStyle) {
	    super(context, attrs, defStyle);
	    init(context);
	}
	
	/**
	 * update from game state
	 */
	public void updateState(){
		if(state == State.nothing)
			this.setText("");
		else if (state != State.corrupted)
			this.setText(game.xoChar[state.index]);
	}
	
	/**
	 * init
	 * @param context
	 */
	public void init(Context context){
		setListener();
		state = State.nothing;
		game = (MainActivity)context;
	}

	/**
	 * add action listener
	 */
	public void setListener(){
		this.setOnClickListener(this);
	}
	
	/**
	 * reset new game
	 */
	public void reset(){
		state = State.nothing;
		updateState();
	}

	/* (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	public void onClick(View v) {
		if(state == State.nothing && !game.gameFinished)
		{
			if(game.playerOneTurn)
				state = State.player1;
			else
				state = State.player2;
			updateState();
			game.verify(java.util.Arrays.asList(game.buttons).indexOf(this));
			game.playerOneTurn = !game.playerOneTurn;
		}
	}
}
