package de.renew.formalism.function;

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

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

/**
 * A function that sets the value of a static field.
 */
public class StaticFieldWriteFunction implements Function {

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

    /**
     * Creates an instance of this class from a field.
     *
     * @param field a field
     */
    public StaticFieldWriteFunction(Field field) {
        this._field = field;
    }

    @Override
    public Object function(Object param) throws Impossible {
        try {
            // Unlike in FieldFunction we must not deal with the special
            // field length for arrays, which cannot be assigned.
            _field.set(null, Value.unvalueAndCast(param, _field.getType()));
            return param;
        } catch (Exception e) {
            throw new Impossible("Exception occured during method call: " + e);
        }
    }

    /**
     * Serialization method, behaves like default writeObject
     * method. Stores the not-really-transient field 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.writeField(out, _field);
    }

    /**
     * Deserialization method, behaves like default readObject
     * method. Restores the not-really-transient field 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();
        _field = ReflectionSerializer.readField(in);
    }
}