package de.renew.formalism.function;

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

import de.renew.util.ReflectionSerializer;

/**
 * Describes a method and allows invoking it.
 */
public class MethodFunction extends AbstractMethodFunction {

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

    /**
     * Creates an instance of this class describing a method using reflections.
     *
     * @param method the method
     */
    public MethodFunction(Method method) {
        this._method = method;
    }

    @Override
    public Object doFunction(Object obj, Object[] paramArr) throws Exception {
        return Executor.executeMethod(_method, obj, paramArr);
    }

    /**
     * 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);
    }

    @Override
    public String toString() {
        return "MethodFunc: " + _method.toString();
    }
}