package org.vostan.sokoban;

import android.app.Application;
import android.content.SharedPreferences;
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";
	public 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+10);
	}
	//
	//	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() );
	}
	public Puzzle getPrevPuzzle()
	{
		if ( current_level != MIN_LEVEL )
			return getPuzzle( getCurrentLevel()-1 );
		else
			return null;
	}
	public Puzzle getNextPuzzle()
	{
		if ( current_level != achieved_level )
			return getPuzzle( getCurrentLevel()+1 );
		else
			return null;
	}
	//
	//	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.
	//
	public void setCurrentLevel( int l )
	{
		if ( l > achieved_level )
			l = MIN_LEVEL;
		if ( l < MIN_LEVEL )
			l = achieved_level;
		if ( l != current_level )
		{
			current_level = l;
			prefsEdit.putInt("current_level", current_level);
			prefsEdit.apply();
			if ( !prefs.edit().commit() )
				Log.d(TAG, "prefs.edit().commit() failed.");
		}
	}
	//
	//	Set achieved level.
	//
	public void advanceAchivedLevel( int l )
	{
		if ( l > max_level )
			l = max_level;
		if ( l > achieved_level )
		{
			achieved_level = l;
			prefsEdit.putInt("achieved_level", achieved_level);
			prefsEdit.apply();
			if ( !prefs.edit().commit() )
				Log.d(TAG, "prefs.edit().commit() failed.");
		}
	}
}
