package modules.image;

import com.one.ModuleRegistry;
import com.one.OptionStorage;
import com.vmx.Locale;
import filemanager.main;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
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;

public class ImageOptions implements CommandListener, OptionStorage
{
	public static final int OPTIONS_VERSION = 1;

	public static int rotateMode = 0;
	public static boolean scaleImages = true;
	public static boolean useAccelerometer = false;

	protected Object parent;

	protected ChoiceGroup cgPlayer;

	public void showEditor(Object parent)
	{
		this.parent = parent;
		
		restoreOptions();
		
		Form form = new Form(ModuleRegistry.getModuleName(getClass().getName()));

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

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

		form.append(cgPlayer);

		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)
		{
			useAccelerometer = cgPlayer.isSelected(0);

			saveOptions();
		}

		main.dsp.setCurrent(parent);
	}

	public void restoreOptions()
	{
		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;
			}

			rotateMode = dis.readInt();
			scaleImages = dis.readBoolean();
			useAccelerometer = dis.readBoolean();

			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(rotateMode);
			dos.writeBoolean(scaleImages);
			dos.writeBoolean(useAccelerometer);

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

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