package modules.langpack;

import com.one.Application;
import com.one.IniFile;
import com.one.PlayList;
import com.one.TextProcessor;
import com.one.file.Connector;
import com.one.file.FileConnection;
import com.vmx.InputStreamDecoder;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Enumeration;

public class StringPacker implements Application
{
	public void openFile(String filename, PlayList filelist) throws IOException
	{
		FileConnection fc = (FileConnection)Connector.open("file:///" + filename);

		String tempname = Connector.createTempFile(filename, true);
		FileConnection temp = (FileConnection)Connector.open("file:///" + tempname);
		temp.create();

		InputStreamDecoder isd = InputStreamDecoder.getFileDecoder(fc);
		IniFile ini = new IniFile(isd, false);
		isd.close();

		DataOutputStream dos = temp.openDataOutputStream();

		Enumeration sections = ini.listSections();
		String section = null;

		int count = 0;

		while(sections.hasMoreElements())
		{
			section = (String)sections.nextElement();

			try
			{
				count = Integer.parseInt(section);

				if(count > 0)
				{
					break;
				}
			}
			catch(NumberFormatException nfe)
			{
			}
		}

		dos.writeInt(count);

		String text;

		for(int i = 0; i < count; i++)
		{
			text = ini.getRecord(section, Integer.toString(i));

			if(text != null)
			{
				dos.writeUTF(TextProcessor.unescapeString(text));
			}
			else
			{
				System.out.println("String " + Integer.toString(i) + " is missing!");
				dos.writeUTF("");
			}
		}

		dos.close();

		filename = fc.getName();
		fc.delete();
		fc.close();

		temp.rename(filename);
		temp.close();

		Connector.releaseTempFile(tempname);
	}
}
