/*
    JPC: A x86 PC Hardware Emulator for a pure Java Virtual Machine
    Release Version 2.0

    A project from the Physics Dept, The University of Oxford

    Copyright (C) 2007 Isis Innovation Limited

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 2 as published by
    the Free Software Foundation.

    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.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 
    Details (including contact information) can be found at: 

    www.physics.ox.ac.uk/jpc
*/

package org.jpc.emulator.memory.codeblock.qanddcompiler;

import java.io.*;
import java.util.*;

import org.jpc.emulator.memory.codeblock.*;
import org.jpc.classfile.*;

public class QandDClassFileBuilder extends ClassLoader
{
    private static Hashtable classes;
    private static ByteArrayInputStream bis;

    private static final QandDClassFileBuilder mySelf;
    static {
        mySelf = new QandDClassFileBuilder();
    }

    private QandDClassFileBuilder()
    {
        super(ClassLoader.getSystemClassLoader());
        classes = new Hashtable();

        byte[] classBytes = null;
        String classRes = RealModeSkeletonBlock.class.getName().replace(".", "/")+".class";
        try
        {
            InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(classRes);
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            
            while (true)
            {
                int ch = in.read();
                if (ch < 0)
                    break;
                bout.write((byte) ch);
            }

            classBytes = bout.toByteArray();
        }
        catch (Exception e)
        {
            System.out.println("Oh Shit "+e);
        }
            
        bis = new ByteArrayInputStream(classBytes);
    }

    public Class findClass(String name) throws ClassNotFoundException
    {
	Class myClass = (Class)classes.get(name);
        if (myClass != null)
            return myClass;
        else
	    throw new ClassNotFoundException(name);
    }


    public static ClassFile createNewSkeletonClass()
    {
        ClassFile cf = new ClassFile();
        
        try 
        {
            bis.reset();
            DataInputStream dis = new DataInputStream(bis);
            cf.read(dis);
        }
        catch (IOException e)
        {
            System.out.println("read error: " + e);
        }

        return cf;
    }

    public static CodeBlock instantiateClass(ClassFile cf)
    {
        cf.update();
        String className = cf.getClassName();

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try 
        {           
            cf.write(new DataOutputStream(bos));
        }
        catch (IOException e)
        {
            System.out.println("write error: " + e);
        }

        byte[] classBytes = bos.toByteArray();

//         try
//         {
//             OutputStream dump = new FileOutputStream(className + ".class");
//             dump.write(classBytes);
//             dump.close();
//         } 
//         catch (Exception e) 
//         {
//             System.err.println("Failed writing class");
//         }
        
        
        Class codeBlockClass = mySelf.defineClass(className, classBytes, 0, classBytes.length);
        classes.put(className, codeBlockClass);

        CodeBlock compiledBlock = null;
        try
        {
            compiledBlock = (CodeBlock) codeBlockClass.newInstance();
        }
        catch (InstantiationException e)
        {
            throw new IllegalStateException("Could not instantiate class", e);
        }
        catch (IllegalAccessException e)
        {
            throw new IllegalStateException("Could not instantiate class", e);
        }
        
        return compiledBlock;
    }
}
