package org.dyndns.vahagn.sokoban;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

public class App extends Application
{	
	public static final String TAG = "Sokoban";
	public static final String PREFS = "org.dyndns.vahagn.sokoban.prefs";
	static final int MIN_LEVEL = 1;
	
	private static App mApp = null;
	protected PuzzleContainer pc;
	protected int current_level;
	protected int achieved_level;
	protected int max_level;
	protected SharedPreferences prefs;
	protected SharedPreferences.Editor prefsEdit;
	
	/* 
	 * 
	 */
	@Override
	public void onCreate()
	{
	    super.onCreate();
	    mApp = this;
	    pc = new PuzzleContainer();
		prefs = getSharedPreferences(PREFS, MODE_PRIVATE);
		prefsEdit = prefs.edit();
	    max_level = pc.getCount();
		current_level = prefs.getInt("current_level", MIN_LEVEL);
		achieved_level = prefs.getInt("achieved_level", MIN_LEVEL);
	}
	//
	//	This is a singleton object.
	//
	public static App theApp()
	{
	    return mApp;
	}
	//
	//	Puzzles.
	//
	public Puzzle getPuzzle( int level )
	{
		return pc.getPuzzle( level-1 );
	}
	public Puzzle getCurrentPuzzle()
	{
		return getPuzzle( getCurrentLevel() );
	}
	//
	//	Provide amount of puzzles.
	//
	public final int getPuzzleCount()
	{
		return max_level;
	}
	//
	//	Provide highest solved puzzle.
	//
	public final int getAchivedLevel()
	{
		return achieved_level;
	}
	//
	//	Provide last played puzzle.
	//
	public final int getCurrentLevel()
	{
		return current_level;
	}
	//
	//	Set the current puzzle level. It deons't alter 
	//
	public void setCurrentLevel( int l )
	{
		if ( current_level != l )
		{
			current_level = l;
			prefsEdit.putInt("current_level", current_level);
			prefsEdit.apply();
			if ( !prefs.edit().commit() )
				Log.d(TAG, "prefs.edit().commit() failed.");
		}
	}
	//
	//	Advances current level. It also reviews achived level if the
	//	new level is bigger than achieved level.
	//
	public void advanceCurrentLevel()
	{
		int new_level = current_level+1;
		if ( new_level == max_level )
			new_level = MIN_LEVEL;
		if ( new_level > achieved_level )
		{
			achieved_level = new_level;
			prefsEdit.putInt("achieved_level", achieved_level);
			//	Don't call apply() here since the call below 
			//	to setCurrentLevel() will do that.
		}
		setCurrentLevel(new_level);
	}

}
