/*
 * Copyright (C) 2002 - 2007 Lehrstuhl Grafische Systeme, BTU Cottbus
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 3
 * of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package de.grogra.xl.compiler;

import java.io.IOException;
import java.util.HashSet;

import de.grogra.grammar.ASTWithToken;
import de.grogra.grammar.Tokenizer;
import de.grogra.reflect.Field;
import de.grogra.reflect.Member;
import de.grogra.reflect.Method;
import de.grogra.reflect.Reflection;
import de.grogra.reflect.Type;
import de.grogra.util.DetailedException;
import de.grogra.util.Utils;
import de.grogra.xl.compiler.scope.ClassPath;
import de.grogra.xl.compiler.scope.CompilationUnitScope;
import de.grogra.xl.compiler.scope.Package;
import de.grogra.xl.compiler.scope.PackageImportOnDemand;
import de.grogra.xl.compiler.scope.Scope;
import de.grogra.xl.parser.Parser;
import de.grogra.xl.parser.XLParser;
import de.grogra.xl.parser.XLTokenTypes;

public abstract class Shell
{
	public static final String SHELL_PACKAGE = "$shell$";
	public static final String SHELL_CLASS = "Shell";

	private ClassPath path;
	private CClass shell;
	private CompilationUnitScope lastScope;
	private Type lastShell;

	public Shell (ClassPath path)
	{
		this.path = path;
		reset ();
	}

	public void reset ()
	{
		shell = new CClass (SHELL_CLASS, SHELL_PACKAGE + '.' + SHELL_CLASS, Member.PUBLIC | Member.ABSTRACT, null, true);
		shell.initSupertype (Type.OBJECT);
		shell.initTypeLoader (path);
		lastScope = null;
		lastShell = null;
	}

	public static XLParser createParser (Tokenizer t)
	{
		XLParser p = new XLParser (t);
		p.setShell (new ASTWithToken (XLTokenTypes.IDENT, SHELL_PACKAGE), SHELL_CLASS);
		return p;
	}

	public static Scope extractImports (CompilationUnitScope scope)
	{
		for (Scope s = scope; s != null; s = s.getEnclosingScope ())
		{
			if (s.getEnclosingScope () instanceof Package)
			{
				s.insert (null);
				break;
			}
		}
		return scope.getEnclosingScope ();
	}

	protected void clearReferences ()
	{
		path = null;
		shell = null;
		lastScope = null;
		lastShell = null;
	}

	protected ClassPath getClassPath ()
	{
		return path;
	}

	protected ClassLoader createClassLoader ()
	{
		return path.getClassLoader ();
	}

	protected abstract void printlnError (String msg);

	protected abstract Type compile (ClassLoader parentLoader, ClassPath path, CompilationUnitScope lastScope, CClass shell, String cmd,
									 CompilationUnitScope[] newScopeOut) throws IOException;

	protected abstract void invokeCompiledMethod (Method method) throws Exception;


	public Throwable execute (String cmd)
	{
		Throwable ex = null;
		if ((shell != null) && (cmd.trim ().length () > 0))
		{
			for (int i = shell.getDeclaredMethodCount () - 1; i >= 0; i--)
			{
				shell.removeMethod (shell.getDeclaredMethod (i));
			}
			ClassLoader cl = createClassLoader ();
			HashSet<String> removedFields = new HashSet<String> ();
			HashSet<Field> oldFields = new HashSet<Field> ();
			for (int i = shell.getDeclaredFieldCount () - 1; i >= 0; i--)
			{
				Field x = shell.getDeclaredField (i);
				if (!(Reflection.isPrimitive (x.getType ()) || Reflection.canLoad (cl, x.getType ().getImplementationClass ())))
				{
					shell.removeField (x);
					removedFields.add (x.getDescriptor ());
				}
				else
				{
					oldFields.add (x);
				}
			}
			Type compiledShell;
			CompilationUnitScope newScope;
			try
			{
				if (cmd.charAt (cmd.length () - 1) != ';')
				{
					cmd += (cmd.indexOf ("//") >= 0) ? "\n;" : ";";
				}
				CompilationUnitScope[] newScopeArray = {null};
				compiledShell = compile (cl, path, lastScope, shell, cmd, newScopeArray);
				newScope = newScopeArray[0];
			}
			catch (IOException e)
			{
				for (int i = shell.getDeclaredFieldCount () - 1; i >= 0; i--)
				{
					Field x = shell.getDeclaredField (i);
					if (!oldFields.contains (x))
					{
						shell.removeField (x);
					}
				}
				compiledShell = null;
				newScope = null;
				Throwable t = Utils.getMainException (e);
				if (t instanceof DetailedException)
				{
					printlnError (((DetailedException) t).getDetailedMessage (false));
				}
				else
				{
					ex = t;
				}
			}
			if (newScope != null)
			{
				lastScope = newScope;
				if (lastShell != null)
				{
					for (int i = lastShell.getDeclaredFieldCount () - 1; i >= 0; i--)
					{
						Field x = lastShell.getDeclaredField (i);
						if ((x.getModifiers () & (Member.PUBLIC | Member.SYNTHETIC))
							== Member.PUBLIC)
						{
							Field y = Reflection.getDeclaredField (
								compiledShell, x.getDescriptor ());
							if ((y != null) && !removedFields.contains (x.getDescriptor ()))
							{
								try
								{
									Object value = Reflection.get (null, x);
									Reflection.set (null, y, value);
								}
								catch (Exception e)
								{
									printlnError (x.getDescriptor () + " " + e);
								}
							}
						}
					}
				}
				lastShell = compiledShell;
				Method m = Reflection.getDeclaredMethod (compiledShell, "execute");
				if (m != null)
				{
					try
					{
						invokeCompiledMethod (m);
					}
					catch (Exception e)
					{
						ex = e;
					}
				}
			}
		}
		if (ex != null)
		{
			printlnError (ex.toString ());
		}
		return ex;
	}
}
