package modules.options;

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.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;

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

	protected Object parent;

	protected Gauge gCompLevel;

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

		restoreOptions();

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

		gCompLevel = new Gauge(Locale.getString(this, Locale.COMPRESSION_LEVEL), true, BZip2CompressorOutputStream.MAX_BLOCKSIZE - BZip2CompressorOutputStream.MIN_BLOCKSIZE, BZip2CompressorOutputStream.getDefaultBlockSize() - BZip2CompressorOutputStream.MIN_BLOCKSIZE);

		form.append(gCompLevel);

		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)
		{
			BZip2CompressorOutputStream.setDefaultBlockSize(gCompLevel.getValue() + BZip2CompressorOutputStream.MIN_BLOCKSIZE);

			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;
			}

			BZip2CompressorOutputStream.setDefaultBlockSize(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(BZip2CompressorOutputStream.getDefaultBlockSize());

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

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