package modules.sfc;

import com.one.Application;
import com.one.Operation;
import com.one.PlayList;
import com.one.file.Connector;
import com.one.file.FileConnection;
import com.vmx.AuxClass;
import com.vmx.Locale;
import filemanager.TemplateManager;
import filemanager.TemplateTextField;
import filemanager.filesystem;
import filemanager.main;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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 abstract class SFCModule implements Application, CommandListener
{
	protected Form form;
	protected TextField tbExtractTo;
	protected Object parent;

	public abstract InputStream getCompressorInputStream(InputStream base) throws IOException;

	public void openFile(String filename, PlayList filelist)
	{
		form = new Form(Locale.getString(this, Locale.EXTRACT_TO));

		String newname = filename.substring(filename.lastIndexOf('/') + 1);
		int index = newname.lastIndexOf('.');

		if(index > 0)
		{
			newname = newname.substring(0, index);
		}
		else
		{
			newname = AuxClass.timeToFileName(-1);
		}

		tbExtractTo = new TemplateTextField(null, main.currentPath + newname, 1024, TextField.ANY);
		form.append(tbExtractTo);

		form.addCommand(new Command(Locale.getString(this, Locale.OK_CMD), Command.OK, 1));
		form.addCommand(new Command(Locale.getString(this, Locale.CANCEL_CMD), Command.CANCEL, 3));
		form.setCommandListener(this);

		parent = main.dsp.getCurrent();
		main.dsp.setCurrent(form);
	}

	public void commandAction(Command c, Displayable dp)
	{
		if(c.getCommandType() == Command.OK)
		{
			Operation operation = new Operation()
			{
				public void run()
				{
					callback.setText(Locale.getString(this, Locale.UNPACKING_FILE, main.currentFile));

					try
					{
						String filename = tbExtractTo.getString();
						String path = filename.substring(0, filename.lastIndexOf('/') + 1);

						if(!filesystem.isFileExist(path))
						{
							filesystem.makeNewDir(path);
						}

						FileConnection fc = (FileConnection)Connector.open("file:///" + filename);

						if(fc.exists())
						{
							fc.truncate(0);
						}
						else
						{
							fc.create();
						}

						OutputStream os = fc.openOutputStream();
						InputStream is = getCompressorInputStream(Connector.openInputStream("file:///" + main.currentPath + main.currentFile));

						AuxClass.copyStream(is, os, callback);

						is.close();
						os.close();
						fc.close();

						main.currentFile = filename.substring(filename.lastIndexOf('/') + 1);
					}
					catch(Exception e)
					{
						logError(e);
					}
				}
			};

			operation.start();
		}
		else if(c.getCommandType() == Command.ITEM)
		{
			TemplateManager.showTemplateList(tbExtractTo, form);
		}
		else
		{
			main.dsp.setCurrent(parent);
		}
	}
}