package modules.audio;

import com.one.ModulePlayer;
import com.one.ModuleRegistry;
import com.one.OptionStorage;
import com.vmx.Locale;
import com.vmx.StringEncoder;
import filemanager.main;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;

public class AudioOptions implements CommandListener, OptionStorage
{
	public static final int OPTIONS_VERSION = 5;

	public static int volume = 100; // громкость аудио плейера
	public static boolean muted = false; // отключен звук в аудиоплейере?
	public static int modBufSize = 10;
	public static int modSampleRate = 0;
	public static int modQuality = 1;
	public static int playerVisualMode = 0;
	public static int playerVisualVariant = 0;
	public static boolean useAccelerometer = false;
	public static boolean shufflePlay = false;
	public static boolean showPlayProgress = true;
	public static int id3Enc = 0;
	public static String metaDataFormat = "author, title, album";
	public static boolean showMetaKeys = false;

	// Уровни эквалайзера
	public static Hashtable eqlevels = new Hashtable();

	protected Object parent;

	protected ChoiceGroup cgPlayer;
	protected ChoiceGroup cgModSampleRate;
	protected ChoiceGroup cgModQuality;
	//protected ChoiceGroup cgID3Enc;

	protected TextField tfModBufSize;
	protected TextField tfMetaDataFormat;

	public void showEditor(Object parent)
	{
		this.parent = parent;

		restoreOptions();

		Form form = new Form(ModuleRegistry.getModuleName(getClass().getName()));

		// *** Настройки плеера ***
		cgPlayer = new ChoiceGroup(Locale.getString(this, Locale.PREF_PLAYER_SETUP), Choice.MULTIPLE);

		// Показывать ключи метаданных
		cgPlayer.append(Locale.getString(this, Locale.PREF_SHOW_META_KEYS), null);
		cgPlayer.setSelectedIndex(0, showMetaKeys);

		// Показывать прогресс-бар при воспроизведении
		cgPlayer.append(Locale.getString(this, Locale.PREF_SHOW_PLAY_PROGRESS), null);
		cgPlayer.setSelectedIndex(1, showPlayProgress);

		// Использовать акселерометр
		cgPlayer.append(Locale.getString(this, Locale.PREF_USE_ACCELEROMETER), null);
		cgPlayer.setSelectedIndex(2, useAccelerometer);

		// *** Размер буфера плеера ***
		tfModBufSize = new TextField(Locale.getString(this, Locale.PREF_MOD_BUF_SIZE), Integer.toString(modBufSize), 4, TextField.NUMERIC);

		// *** Частота дискретизации модулей ***
		cgModSampleRate = new ChoiceGroup(Locale.getString(this, Locale.PREF_MOD_SAMPLE_RATE), Choice.EXCLUSIVE);

		for(int i = 0; i < ModulePlayer.SAMPLE_RATES.length; i++)
		{
			cgModSampleRate.append(Integer.toString(ModulePlayer.SAMPLE_RATES[i]) + " " + Locale.getString(this, Locale.HZ), null);
		}

		cgModSampleRate.setSelectedIndex(modSampleRate, true);

		// *** Качество модулей ***
		cgModQuality = new ChoiceGroup(Locale.getString(this, Locale.PREF_MOD_QUALITY), Choice.EXCLUSIVE);

		cgModQuality.append(Locale.getString(this, Locale.QUALITY_LOW), null);
		cgModQuality.append(Locale.getString(this, Locale.QUALITY_MEDIUM), null);
		cgModQuality.append(Locale.getString(this, Locale.QUALITY_HIGH), null);

		cgModQuality.setSelectedIndex(modQuality, true);

		tfMetaDataFormat = new TextField(Locale.getString(this, Locale.METADATA_FORMAT), metaDataFormat, 256, TextField.ANY);

//		// *** Кодировка ID3 ***
//		cgID3Enc = new ChoiceGroup(Locale.getString(this, Locale.PREF_ID3_ENCODING), Choice.EXCLUSIVE);
//
//		cgID3Enc.append(StringEncoder.ENC_NAME_UTF8, null);
//
//		for(int i = 0; i < StringEncoder.encnames.length; i++)
//		{
//			cgID3Enc.append(StringEncoder.encnames[i], null);
//		}
//
//		if(id3Enc == StringEncoder.ENC_UTF8)
//		{
//			cgID3Enc.setSelectedIndex(0, true);
//		}
//		else
//		{
//			cgID3Enc.setSelectedIndex(id3Enc + 1, true);
//		}

		form.append(cgPlayer);
		form.append(tfMetaDataFormat);
		form.append(tfModBufSize);
		form.append(cgModSampleRate);
		form.append(cgModQuality);
		//form.append(cgID3Enc);

		form.addCommand(new Command(Locale.getString(this, Locale.OK_CMD), Command.OK, 1));
		form.addCommand(new Command(Locale.getString(this, Locale.CANCEL_CMD), Command.BACK, 2));

		form.setCommandListener(this);
		
		main.dsp.setCurrent(form);
	}

	public void commandAction(Command c, Displayable d)
	{
		if(c.getCommandType() == Command.OK)
		{
			showMetaKeys = cgPlayer.isSelected(0);
			showPlayProgress = cgPlayer.isSelected(1);
			useAccelerometer = cgPlayer.isSelected(2);

			modBufSize = Integer.parseInt(tfModBufSize.getString());
			modSampleRate = cgModSampleRate.getSelectedIndex();
			modQuality = cgModQuality.getSelectedIndex();

			metaDataFormat = tfMetaDataFormat.getString();

//			if(cgID3Enc.getSelectedIndex() == 0)
//			{
//				id3Enc = StringEncoder.ENC_UTF8;
//			}
//			else
//			{
//				id3Enc = cgID3Enc.getSelectedIndex() - 1;
//			}

			saveOptions();
		}

		main.dsp.setCurrent(parent);
	}

	public void restoreOptions()
	{
		String s = main.loader.getAppProperty("ID3-Encoding");

		if(s != null)
		{
			id3Enc = StringEncoder.findEncoding(s);
		}

		try
		{
			byte[] data = ModuleRegistry.getModuleData(getClass().getName());

			if(data == null || data.length == 0)
			{
				return;
			}

			DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));

			if(dis.readInt() != OPTIONS_VERSION)
			{
				dis.close();
				return;
			}

			volume = dis.readInt();
			muted = dis.readBoolean();
			modBufSize = dis.readInt();
			modSampleRate = dis.readInt();
			modQuality = dis.readInt();
			playerVisualMode = dis.readInt();
			playerVisualVariant = dis.readInt();
			useAccelerometer = dis.readBoolean();
			shufflePlay = dis.readBoolean();
			showPlayProgress = dis.readBoolean();
			/*id3Enc =*/ dis.readInt();
			metaDataFormat = dis.readUTF();
			showMetaKeys = dis.readBoolean();

			int count = dis.readInt();

			eqlevels.clear();

			for(int i = 0; i < count; i++)
			{
				eqlevels.put(new Integer(dis.readInt()), new Integer(dis.readInt()));
			}

			dis.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	public void saveOptions()
	{
		try
		{
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			DataOutputStream dos = new DataOutputStream(baos);

			dos.writeInt(OPTIONS_VERSION);
			dos.writeInt(volume);
			dos.writeBoolean(muted);
			dos.writeInt(modBufSize);
			dos.writeInt(modSampleRate);
			dos.writeInt(modQuality);
			dos.writeInt(playerVisualMode);
			dos.writeInt(playerVisualVariant);
			dos.writeBoolean(useAccelerometer);
			dos.writeBoolean(shufflePlay);
			dos.writeBoolean(showPlayProgress);
			dos.writeInt(id3Enc);
			dos.writeUTF(metaDataFormat);
			dos.writeBoolean(showMetaKeys);

			dos.writeInt(eqlevels.size());

			Enumeration levels = eqlevels.keys();
			Integer freq, level;

			while(levels.hasMoreElements())
			{
				freq = (Integer)levels.nextElement();
				level = (Integer)eqlevels.get(freq);

				dos.writeInt(freq.intValue());
				dos.writeInt(level.intValue());
			}

			byte[] data = baos.toByteArray();
			dos.close();

			ModuleRegistry.setModuleData(getClass().getName(), data);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}
