package modules.sfc;

import com.one.FileSource;
import com.one.Operation;
import com.one.file.Connector;
import com.one.file.FileConnection;
import com.vmx.AuxClass;
import com.vmx.Locale;
import filemanager.main;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public abstract class SFCFileSource implements FileSource
{
	public abstract OutputStream getCompressorOutputStream(OutputStream base) throws IOException;

	public void createFile(final String filename)
	{
		if(main.currentFile.endsWith("/"))
		{
			throw new IllegalArgumentException("Can't compress a directory, put it into a package first.");
		}

		Operation operation = new Operation()
		{
			public void run()
			{
				callback.setText(Locale.getString(this, Locale.PACKING_FILE, main.currentFile));

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

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

					OutputStream os = getCompressorOutputStream(fc.openOutputStream());
					InputStream is = 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();
	}
}