package filemanager;

import com.one.ErrScreen;
import com.one.FileSystemObject;
import com.one.IniRecord;
import com.one.PaintableObject;
import com.one.Renderer;
import com.vmx.AuxClass;
import com.vmx.InputStreamDecoder;
import com.vmx.Locale;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
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;
import javax.microedition.rms.RecordStore;

public class MimeType implements CommandListener, ListStateListener
{
	protected static Hashtable types;		// MIME типы по расширениям

	protected static Object parent;
	protected static ListMenu list;
	protected static Vector extlist;

	protected static Form form;
	protected static TextField tfExtension;
	protected static TextField tfType;

	protected static Command cmdAdd;
	protected static Command cmdEdit;
	protected static Command cmdDelete;
	protected static Command cmdBack;
	protected static Command cmdOK;
	protected static Command cmdCancel;

	/**
	 * Чтение списка MIME типов.
	 */
	public static void loadTypes()
	{
		if(types == null)
		{
			types = new Hashtable();
		}
		else
		{
			types.clear();
		}

		try
		{
			RecordStore rs = RecordStore.openRecordStore(AuxClass.getStoreName(11), true);

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

				InputStreamDecoder ini = InputStreamDecoder.getResourceDecoder("/config/mime.ini");
				IniRecord record;

				while((record = IniRecord.getNextRecord(ini)) != null)
				{
					addType(record.key, record.value);
				}

				ini.close();

				return;
			}

			DataInputStream dis = new DataInputStream(new ByteArrayInputStream(rs.getRecord(1)));
			rs.closeRecordStore();

			int count = dis.readInt();

			for(int i = 0; i < count; i++)
			{
				addType(dis.readUTF(), dis.readUTF());
			}

			dis.close();
		}
		catch(Exception e)
		{
			ErrScreen.showErrMsg(140, e);
		}
	}

	public static void saveTypes()
	{
		if(types == null)
		{
			return;
		}

		try
		{
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			DataOutputStream dos = new DataOutputStream(baos);

			dos.writeInt(types.size());

			Enumeration extensions = types.keys();
			String ext;

			while(extensions.hasMoreElements())
			{
				ext = (String)extensions.nextElement();

				dos.writeUTF(ext);
				dos.writeUTF(getType(ext));
			}

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

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

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

			rs.closeRecordStore();
		}
		catch(Exception e)
		{
			ErrScreen.showErrMsg(139, e);
		}
	}

	/**
	 * Определяем MIME тип файла по расширению.
	 */
	public static String getType(String fileName)
	{
		if(types == null)
		{
			loadTypes();
		}

		return (String)types.get(AuxClass.getFileExtension(fileName).toLowerCase());
	}

	public static void addType(String ext, String type)
	{
		if(types == null)
		{
			loadTypes();
		}

		types.put(ext.toLowerCase(), type);
	}

	public static void deleteType(String ext)
	{
		if(types == null)
		{
			loadTypes();
		}

		types.remove(ext);
	}

	public static void showTypeList(Object parent)
	{
		MimeType.parent = parent;

		createUI();
		main.dsp.setCurrent(list);
	}

	public static void createUI()
	{
		if(list != null)
		{
			return;
		}

		Object object = MimeType.class.getName();
		MimeType mt = new MimeType();

		extlist = new Vector();

		list = new ListMenu();
		list.setTitle(Locale.getString(object, Locale.MIME_TYPES_CMD));
		//list.setSubTitle(Locale.getString(object, Locale.ROOT), false);

		cmdAdd = new Command(Locale.getString(object, Locale.ADD_CMD), Command.OK, 1);
		cmdEdit = new Command(Locale.getString(object, Locale.EDIT_CMD), Command.OK, 2);
		cmdDelete = new Command(Locale.getString(object, Locale.DELETE_CMD), Command.OK, 3);
		cmdBack = new Command(Locale.getString(object, Locale.BACK_CMD), Command.BACK, 4);
		cmdOK = new Command(Locale.getString(object, Locale.OK_CMD), Command.OK, 1);
		cmdCancel = new Command(Locale.getString(object, Locale.CANCEL_CMD), Command.CANCEL, 2);

		list.addCommand(cmdAdd);
		list.addCommand(cmdBack);
		list.setCommandListener((CommandListener)mt);
		list.setStateListener((ListStateListener)mt);

		form = new Form(Locale.getString(object, Locale.EDIT_CMD));

		tfExtension = new TextField(Locale.getString(object, Locale.FILE_TYPE), "", 32, TextField.ANY);
		tfType = new TextField(Locale.getString(object, Locale.MIME_TYPE), "", 256, TextField.ANY);

		form.append(tfExtension);
		form.append(tfType);

		form.addCommand(cmdOK);
		form.addCommand(cmdCancel);
		form.setCommandListener((CommandListener)mt);

		updateList();
	}
	
	public static void updateList()
	{
		if(types == null)
		{
			loadTypes();
		}
		
		list.deleteAll();
		extlist.removeAllElements();
		
		Enumeration extensions = FileSystemObject.sortFileList(types.keys());
		String ext;

		while(extensions.hasMoreElements())
		{
			ext = (String)extensions.nextElement();

			extlist.addElement(ext);
			list.append(ext); // + " - " + getType(ext));
		}

		if(list.size() > 0)
		{
			list.addCommand(cmdEdit);
			list.addCommand(cmdDelete);
		}
		else
		{
			list.removeCommand(cmdEdit);
			list.removeCommand(cmdDelete);
		}
	}

	public void commandAction(Command c, Displayable dp)
	{
		if(dp instanceof Renderer)
		{
			PaintableObject po = ((Renderer)dp).getCurrent();

			if(po == list)
			{
				if(c == cmdAdd)
				{
					tfExtension.setString("");
					tfType.setString("");

					main.dsp.setCurrent(form);
				}
				else if(c == cmdEdit)
				{
					String ext = (String)extlist.elementAt(list.getSelectedIndex());

					tfExtension.setString(ext);
					tfType.setString(getType(ext));

					main.dsp.setCurrent(form);
				}
				else if(c == cmdDelete)
				{
					deleteType((String)extlist.elementAt(list.getSelectedIndex()));
					updateList();
				}
				else if(c == cmdBack)
				{
					main.dsp.setCurrent(parent);
				}
			}
		}
		else if(dp == form)
		{
			if(c == cmdOK)
			{
				if(tfExtension.size() == 0 || tfType.size() == 0)
				{
					return;
				}

				String ext = tfExtension.getString();

				deleteType(ext);
				addType(ext, tfType.getString());

				updateList();
			}

			main.dsp.setCurrent(list);
		}
	}

	public void listStateChanged(ListMenu list, int action)
	{
		if(list.size() > 0)
		{
			list.setSubTitle(getType((String)extlist.elementAt(list.getSelectedIndex())), true);
		}
		else
		{
			list.setSubTitle("", false);
		}
	}
}