package org.vostan.sokoban;

import java.io.InputStream;
import java.io.IOException;
import static org.vostan.sokoban.App.theApp;

import org.vostan.sokoban.R;

public class PuzzleContainer
{
	protected int count;
	
	/*
	 * Load puzzle from the puzzle.bin.
	 */
	public Puzzle getPuzzle( int i )
	{try{
		InputStream is = theApp().getResources().openRawResource(R.raw.puzzles);

		//
		//	Read amount of puzzles.
		//
		count = read_i32(is);
		if ( i >= count )
			return null;
		//
		//	Read the offset.
		//
		is.skip( i*4 );
		int offset = read_i32(is);
		//
		//	Jump to the offset and read the puzzle.
		//
		is.skip( offset - 4 - (i+1)*4);
		Puzzle p = new Puzzle( is );
		//
		//	Finally return the puzzle and we are done.
		//
		return p;
	}
	catch ( java.lang.Exception e )
	{
		//Log.d(TAG, "Exception: " + e.getMessage() );
		e.printStackTrace();
		return null;
	}}
	//
	//	Retrive amount of puzzles.
	//
	public int getCount()
	{try{
		if ( count == 0 )
		{
			InputStream is = theApp().getResources().openRawResource(R.raw.puzzles);
			count = read_i32(is);
		}
		return count;
	}
	catch ( java.lang.Exception e )
	{
		//Log.d(TAG, "Exception: " + e.getMessage() );
		e.printStackTrace();
		return 0;
	}}
	//
	//	Helper function to read little endian 32bit integer.
	//
	protected int read_i32( InputStream is ) throws IOException
	{
		int i = is.read();
		i |= is.read() << 8;
		i |= is.read() << 16;
		i |= is.read() << 24;
		return i;
	}
}
