package org.luaj.vm2.luajc;

import org.luaj.vm2.LuaClosure;
import org.luaj.vm2.LuaFunction;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Prototype;
import org.luaj.vm2.PrototypeProvider;
import org.luaj.vm2.Varargs;
import org.luaj.vm2.libs.VarArgFunction;

public abstract class LuaJCDelegateFunction extends VarArgFunction implements PrototypeProvider {
	private Prototype prototype;
	private LuaFunction delegate;

	protected abstract String[] prototypeHexChunks();

	private Prototype loadedPrototype() {
		if (prototype == null) {
			prototype = LuaJCDelegateSupport.loadPrototype(prototypeHexChunks(), classnamestub());
		}
		return prototype;
	}

	public Prototype prototype() {
		return loadedPrototype();
	}

	private LuaFunction delegate() {
		if (delegate == null) {
			delegate = new LuaClosure(loadedPrototype(), LuaValue.NIL);
		}
		return delegate;
	}

	public void initupvalue1(LuaValue env) {
		delegate = new LuaClosure(loadedPrototype(), env);
	}

	public Varargs invoke(Varargs args) {
		return delegate().invoke(args);
	}
}
