package de.renew.formalism.function;

import java.io.IOException;
import java.io.Serial;

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


/**
 * A cast function will attempt a cast whenever possible.
 * If primitive values are casted, this might result in loss of
 * precision.
 */
public class CastFunction implements Function {

    /**
     * This field is not really transient, but as <code>java.lang.Class
     * </code>is not always serializable, we have to store it by
     * ourselves.
     **/
    transient Class<?> _clazz;

    /**
     * Constructs an instance of CastFunction for a given class.
     *
     * @param clazz the class
     */
    public CastFunction(Class<?> clazz) {
        this._clazz = clazz;
    }

    @Override
    public Object function(Object arg) throws Impossible {
        Object result = Value.castOrReturnImpossible(_clazz, arg);
        if (result == Value.IMPOSSIBLE_CAST) {
            throw new Impossible();
        }
        return result;
    }

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

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