/**
 * 
 */
package com.anemoff.android.taquin.control;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.anemoff.android.taquin.model.Game;

/**
 * @author anemoff
 * 
 */
public class BoardAdapter extends BaseAdapter implements OnItemClickListener {

	private Context context;
	private Game game;

	/**
	 * Constructeur.
	 * @param context
	 */
	public BoardAdapter(Context context, Game game) {
		this.context = context;
		this.game = game;
	}

	/*
	 * (non-Javadoc)
	 * @see android.widget.Adapter#getCount()
	 */
	@Override
	public int getCount() {
		return game.getBoard().getBoardSize();
	}

	/*
	 * (non-Javadoc)
	 * @see android.widget.Adapter#getItem(int)
	 */
	@Override
	public Object getItem(int position) {
		return game.getBoard().getCell(position);
	}

	/*
	 * (non-Javadoc)
	 * @see android.widget.Adapter#getItemId(int)
	 */
	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	/*
	 * (non-Javadoc)
	 * @see android.widget.Adapter#getView(int, android.view.View,
	 * android.view.ViewGroup)
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// create a new ImageView for each item referenced by the Adapter
		ImageView imageView;
		// if it's not recycled, initialize some attributes
		if (convertView == null) {
			imageView = new ImageView(context);
			//imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
			imageView.setPadding(1, 1, 1, 1);
			imageView.setScaleType(ImageView.ScaleType.FIT_XY);
		} else {
			imageView = (ImageView) convertView;
		}

		imageView.setImageBitmap(game.getBoard().getCell(position).getBitmap());
		
		return imageView;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (!game.isStarted()) {
			// Partie non commencé : click = mélanger + enlever 1 case
			game.start();
			notifyDataSetChanged();
		} else {
			// Partie en cours : click = déplacer
			if (game.moveCell(position)) {
				System.out.println(game.getBoard());
				notifyDataSetChanged();
			}			
		}
	}

}
