package de.renew.formalism.function;

import java.io.IOException;
import java.io.Serial;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import de.renew.expression.Function;
import de.renew.unify.Impossible;
import de.renew.unify.Tuple;
import de.renew.util.ReflectionSerializer;

/**
 * Represents a function that invokes a static method with the provided arguments.
 */
public class StaticMethodFunction implements Function {
    private static final org.apache.log4j.Logger LOGGER =
        org.apache.log4j.Logger.getLogger(StaticMethodFunction.class);

    /**
     * This field is not really transient, but as the reflection
     * classes are not serializable, we have to store it by
     * ourselves.
     **/
    transient Method _method;

    /**
     * Create an instance of this class from a method
     *
     * @param method a method
     */
    public StaticMethodFunction(Method method) {
        if ((method.getModifiers() & Modifier.STATIC) == 0) {
            throw new RuntimeException("Method expected to be static.");
        }
        this._method = method;
    }

    @Override
    public Object function(Object param) throws Impossible {
        Tuple args = (Tuple) param;

        Object[] paramArr = new Object[args.getArity()];
        for (int i = 0; i < paramArr.length; i++) {
            paramArr[i] = args.getComponent(i);
        }

        try {
            return Executor.executeMethod(_method, null, paramArr);
        } catch (Exception e) {
            if (e instanceof InvocationTargetException) {
                Throwable targetException = ((InvocationTargetException) e).getTargetException();
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.error(targetException.getMessage(), targetException);
                    LOGGER.error("while executing " + _method + ".");
                }
                throw new Impossible(
                    "Method call resulted in an exception: " + targetException, targetException);
            } else {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.error(e.getMessage(), e);
                    LOGGER.error("while executing " + _method + ".");
                }
                throw new Impossible("Exception occured during method call: " + e, e);
            }
        }
    }

    /**
     * Serialization method, behaves like default writeObject
     * method. Stores the not-really-transient method field.
     *
     * @param out the output stream to write to
     * @throws IOException if writing the object fails
     **/
    @Serial
    private void writeObject(java.io.ObjectOutputStream out) throws IOException {
        out.defaultWriteObject();
        ReflectionSerializer.writeMethod(out, _method);
    }

    /**
     * Deserialization method, behaves like default readObject
     * method. Restores the not-really-transient method field.
     *
     * @param in the input stream to read from
     * @throws IOException if reading the object fails
     * @throws ClassNotFoundException if a required class is not found during reading
     **/
    @Serial
    private void readObject(java.io.ObjectInputStream in)
        throws IOException, ClassNotFoundException
    {
        in.defaultReadObject();
        _method = ReflectionSerializer.readMethod(in);
    }
}