package filemanager;

import com.one.AbstractFont;
import com.one.GraphicFont;
import com.vmx.AuxClass;
import com.vmx.ProgressCallback;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import javax.microedition.rms.RecordStore;

public class fontConfig
{
	public static String[] fontpaths = new String[AbstractFont.FONT_COUNT];

	static
	{
		for(int i = 0; i < AbstractFont.FONT_COUNT; i++)
		{
			fontpaths[i] = "";
		}
	}

	public static void loadFonts(ProgressCallback callback)
	{
		try
		{
			RecordStore rs = RecordStore.openRecordStore(AuxClass.getStoreName(10), true);

			if(rs.getNumRecords() == 0)
			{
				rs.closeRecordStore();
				return;
			}

			DataInputStream dis = new DataInputStream(new ByteArrayInputStream(rs.getRecord(1)));
			rs.closeRecordStore();
			
//			Hashtable fonts = new Hashtable();
//			AbstractFont font;

			for(int i = 0; i < AbstractFont.FONT_COUNT; i++)
			{
				fontpaths[i] = dis.readUTF();
				
				if(fontpaths[i].length() > 0)
				{
					AbstractFont.setFont(new GraphicFont(fontpaths[i], callback), i);

//					font = (AbstractFont)fonts.get(fontpaths[i]);
//
//					if(font == null)
//					{
//						try
//						{
//							font = new GraphicFont(fontpaths[i], callback);
//							fonts.put(fontpaths[i], font);
//						}
//						catch(Throwable t)
//						{
//							System.out.println("Font " + i + " (" + fontpaths[i] + ") not loaded: " + t.toString());
//						}
//					}
//
//					AbstractFont.setFont(font, i);
				}
			}

			dis.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	public static void saveFonts()
	{
		try
		{
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			DataOutputStream dos = new DataOutputStream(baos);

			for(int i = 0; i < AbstractFont.FONT_COUNT; i++)
			{
				dos.writeUTF(fontpaths[i]);
			}

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

			RecordStore rs = RecordStore.openRecordStore(AuxClass.getStoreName(10), true);

			if(rs.getNumRecords() == 0)
			{
				rs.addRecord(data, 0, data.length);
			}
			else
			{
				rs.setRecord(1, data, 0, data.length);
			}

			rs.closeRecordStore();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	public static void unloadAll()
	{
		AbstractFont font;

		for(int i = 0; i < AbstractFont.FONT_COUNT; i++)
		{
			font = AbstractFont.getFont(i);

			if(font instanceof GraphicFont)
			{
				((GraphicFont)font).unloadAll();
			}
		}
	}

	public static void resetAll()
	{
		for(int i = 0; i < AbstractFont.FONT_COUNT; i++)
		{
			AbstractFont.setFont(null, i);
		}

		System.gc();
	}
}