package com.one;

import com.one.file.Connector;
import com.one.file.FileConnection;
import com.vmx.AuxClass;
import java.io.OutputStream;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.midlet.MIDletStateChangeException;

public class ErrScreen extends Canvas implements CommandListener
{
	public static class ObjectWrap
	{
		public Object object;
	}

	protected static RootLoader loader;
	protected static DisplayManager manager;
	protected static ErrScreen instance;

	protected static String logFileName = "";

	protected ObjectWrap parent;
	
	protected AbstractFont font;
	protected int fnth;
	
	protected int width, height;
	protected int ty;
	
	protected String message;
	protected String[] msglines;

	public static void setLogFileName(String filename)
	{
		if(filename != null)
		{
			logFileName = filename;
		}
		else
		{
			logFileName = "";
		}
	}

	public static String getLogFileName()
	{
		return logFileName;
	}
	
	public static void setRootLoader(RootLoader rl)
	{
		loader = rl;
	}
	
	public static void setDisplayManager(DisplayManager dsp)
	{
		manager = dsp;
	}

	static
	{
		instance = new ErrScreen();
	}

	public static ErrScreen getInstance()
	{
		return instance;
	}
	
	public static void showErrMsg(int errcode, Throwable t)
	{
        instance.append("ERROR", errcode, t);
    }

    public static void showStopMsg(int errcode, Throwable t)
	{
        instance.append("STOP ", errcode, t);
    }

	protected ErrScreen()
	{
		setFullScreenMode(true);
		
		width = getWidth();
		height = getHeight();
		ty = 0;

		font = AbstractFont.getFont(AbstractFont.FACE_MONOSPACE, AbstractFont.STYLE_PLAIN, AbstractFont.SIZE_SMALL);
		fnth = font.getHeight();

		setMessage("");

		parent = new ObjectWrap();
		
		addCommand(new Command("Return", Command.BACK, 1));
		addCommand(new Command("Exit", Command.EXIT, 2));

		setCommandListener(this);
	}
	
	public void append(String msgtype, int errcode, Throwable t)
	{
        StringBuffer msg = new StringBuffer();

		//msg.append(Integer.toHexString(errcode).toUpperCase());
		msg.append(Integer.toString(errcode));

        while(msg.length() < 8)
        {
            msg.insert(0, '0');
        }

		//msg.insert(0, "0x");

		int count = msgtype.length();
		msgtype = msgtype.trim();
		count -= msgtype.length();

		for(int i = 0; i < count; i++)
		{
			msg.insert(0, ' ');
		}

		msg.insert(0, ": ");

		msg.insert(0, msgtype);
		msg.insert(0, "*** ");
        msg.append(" (");
        msg.append(t);
        msg.append(")");

		System.out.println(msg.toString());

		if(t != null)
		{
			if(t instanceof Error)
			{
				try
				{
					throw new RuntimeException(t.toString());
				}
				catch(RuntimeException x)
				{
					x.printStackTrace();
				}
			}
			else
			{
				t.printStackTrace();
			}
		}
		
		setMessage(message + msg.toString() + "\n\n");
		
		if(fnth * msglines.length > height)
		{
			ty = height - fnth * msglines.length;
		}

		if(logFileName != null && logFileName.length() > 0)
		{
			try
			{
				FileConnection fc = (FileConnection)Connector.open("file:///" + logFileName);

				if(!fc.exists())
				{
					fc.create();
				}

				OutputStream os = fc.openOutputStream(fc.fileSize());
				os.write(("[" + AuxClass.timeToString(-1, true) + "] " + msg.toString() + "\r\n").getBytes());
				os.close();

				fc.close();
			}
			catch(Throwable x)
			{
			}
		}

		if(manager != null)
		{
			ProgressBar.hide();
			
			if(manager.getCurrent() != this)
			{
				parent.object = manager.getCurrent();
			}

			manager.setCurrent(this);
		}
	}
	
	public void setMessage(String text)
	{
		message = text;
		msglines = font.splitString(text, width);

		repaint();
	}

	public void setNextDisplayable(Object obj)
	{
		if(obj != instance)
		{
			parent.object = obj;
		}
	}

	public void keyRepeated(int keyCode)
	{
		keyPressed(keyCode);
	}
	
	public void keyPressed(int keyCode)
	{
		if(keyCode == KEY_NUM0)
		{
			ty = 0;
		}
		else
		{
			keyCode = getGameAction(keyCode);

			if(keyCode == UP)
			{
				ty += fnth;
			}
			else if(keyCode == DOWN)
			{
				ty -= fnth;
			}
			else if(keyCode == LEFT)
			{
				ty += height;
			}
			else if(keyCode == RIGHT)
			{
				ty -= height;
			}
			else
			{
				return;
			}
		}

		repaint();
	}

	public void paint(Graphics g)
	{
		g.setColor(0x000080);
		g.fillRect(0, 0, width, height);

		g.setColor(0xFFFFFF);

		for(int i = 0; i < msglines.length; i++)
		{
			font.drawString(g, msglines[i], 0, ty + i * fnth, Graphics.LEFT | Graphics.TOP);
		}
	}

	public void commandAction(Command c, Displayable dp)
	{
		if(c.getCommandType() == Command.BACK)
		{
			if(manager != null && parent.object != null)
			{
				setMessage("");
				ty = 0;
				
				manager.setCurrent(parent);
			}
			else if(loader != null)
			{
				destroyApp();
			}
		}
		else if(loader != null)
		{
			destroyApp();
		}
	}

	protected static void destroyApp()
	{
		try
		{
			loader.destroyApp(false);
		}
		catch(MIDletStateChangeException _)
		{
		}
	}
}
