/*
 * D2A
 * Copyright (C) SatisKia. All rights reserved.
 */

package net.satis.d2a;

import android.media.*;

public class _Music implements MediaPlayer.OnCompletionListener
{
	private _Main _m;
	private int _num;
	private MediaPlayer[] _music;
	private int _index;

	private int _volume;

	public _Music( _Main m, int num )
	{
		_m = m;
		_num = num;
		_music = new MediaPlayer[_num];
		for( int i = 0; i < _num; i++ )
		{
			_music[i] = null;
		}
		_index = -1;

		_volume = 100;
	}

	public void create( int index, int res_id )
	{
		dispose( index );
		_music[index] = MediaPlayer.create( _m, res_id );
//		try
//		{
//			_music[index].prepare();
//		}
//		catch( Exception e ){}
	}

	public void dispose( int index )
	{
		stop();
		if( _music[index] != null )
		{
			try
			{
				_music[index].stop();
				_music[index].release();
				_music[index] = null;
			}
			catch( Exception e ){}
		}
	}

	public void play( int index, boolean loop )
	{
		stop();
		if( _music[index] != null )
		{
			try
			{
				_music[index].setLooping( loop );
				_music[index].setVolume( (float)_volume / 100.0f, (float)_volume / 100.0f );
				_music[index].seekTo( 0 );
				_music[index].start();
				_music[index].setOnCompletionListener( this );
			}
			catch( Exception e ){}
			_index = index;
		}
	}

	public void stop()
	{
		if( _index >= 0 )
		{
			if( _music[_index] != null )
			{
				try
				{
					_music[_index].setOnCompletionListener( null );
					_music[_index].pause();
				}
				catch( Exception e ){}
			}
			_index = -1;
		}
	}

	public void setVolume( int volume )
	{
		_volume = volume;
		if( _index >= 0 )
		{
			if( _music[_index] != null )
			{
				_music[_index].setVolume( (float)_volume / 100.0f, (float)_volume / 100.0f );
			}
		}
	}

	public void release()
	{
		for( int i = 0; i < _num; i++ )
		{
			dispose( i );
		}
		_index = -1;
	}

	public void onCompletion( MediaPlayer mediaPlayer )
	{
		_m.musicComplete( _index );
    }
}
