package com.anemoff.android.taquin.view;

import java.util.Observable;
import java.util.Observer;

import android.app.Activity;
import android.app.Dialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.anemoff.android.taquin.R;
import com.anemoff.android.taquin.control.BoardAdapter;
import com.anemoff.android.taquin.model.Game;

/**
 * 
 * @author anemoff
 * 
 */
public class GameActivity extends Activity implements Observer {

	private Game game;
	private TextView tvMovesCount;
	private BoardAdapter boardAdapter;
	private GridView gridview;

	private static final int ID_GAMEOVER_DIALOG = 0;

	private static final int DEFAULT_SIZE = 3;
	public static final String PREFS_GAME = "prefs_game";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Lire les préférences de jeu
		SharedPreferences prefs = this.getSharedPreferences(PREFS_GAME, 0);
        int boardSize = prefs.getInt("boardSize", DEFAULT_SIZE);
		
		// Créer le gestionnaire de jeu
		game = new Game(this);
		game.addObserver(this);

		// Créer une nouvelle partie
		// TODO utiliser les preférénces de l'appli pour la taille initiale
		game.createBoard(boardSize);

		// Message de bienvenue
		// TODO factoriser code
		Toast toast = Toast.makeText(this, "Touchez l'écran pour commencer",
				Toast.LENGTH_LONG);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();

		// Récuperer les textview
		tvMovesCount = (TextView) findViewById(R.id.tvMovesCount);

		// Créer la vue du taquin
		boardAdapter = new BoardAdapter(this, game);
		gridview = (GridView) findViewById(R.id.gridview);
		gridview.setAdapter(boardAdapter);
		gridview.setOnItemClickListener(boardAdapter);
		gridview.setNumColumns(boardSize);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// Désactiver le mélange si la partie n'a pas commencé
		menu.findItem(R.id.menuShuffle).setEnabled(game.isStarted());
		
		// XXX
		menu.findItem(R.id.menuGallery).setEnabled(false);
		
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menuShuffle:
			// Mélanger l'image courante (= recommencer la partie)
			game.shuffleBoard();
			boardAdapter.notifyDataSetChanged();
			return true;

		case R.id.menuSize3:
			// Taille 3x3
			changeBoardSize(3);
			return true;

		case R.id.menuSize4:
			// Taille 4x4
			changeBoardSize(4);
			return true;

		case R.id.menuSize5:
			// Taille 5x5
			changeBoardSize(5);
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case ID_GAMEOVER_DIALOG:
			// Dialogue de fin de partie
			Dialog dialog = new Dialog(this);
			dialog.setContentView(R.layout.gameover);
			// dialog.setTitle("Partie terminée");
			return dialog;
		}
		return super.onCreateDialog(id);
	}

	@Override
	public void update(Observable obs, Object obj) {
		if (obs instanceof Game && obs != null) {
			Game game = (Game) obs;
			tvMovesCount.setText("Déplacements: " + game.getMoves());

			if (game.isGameOver()) {
				showDialog(ID_GAMEOVER_DIALOG);
			}
		}
	}

	/**
	 * Changer la taille du taquin (nb colonnes = nb lignes).
	 * 
	 * @param newSize
	 *            nouvelle taille
	 */
	private void changeBoardSize(int newSize) {
		if (game.getBoard().getBoardSize() != newSize) {

			// TODO factoriser code
			Toast toast = Toast.makeText(this,
					"Touchez l'écran pour commencer", Toast.LENGTH_LONG);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();

			game.changeSize(newSize);
			gridview.setNumColumns(newSize);

			// Sauvegarder la taille du plateau
			SharedPreferences prefs = this.getSharedPreferences(PREFS_GAME, 0);
			SharedPreferences.Editor editor = prefs.edit();
			editor.putInt("boardSize", newSize);
			editor.commit();
		}
	}

}