package de.uni_hamburg.fs;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


class BeanFeature extends JavaFeature {
    public static final org.apache.log4j.Logger LOGGER =
        org.apache.log4j.Logger.getLogger(BeanFeature.class);
    private Method _get;
    private Method _set;

    BeanFeature(Method get, Method set) {
        this._get = get;
        this._set = set;
    }

    @Override
    Class<?> getJavaClass() {
        return _get.getReturnType();
    }

    @Override
    Object getObjectValue(Object javaObject) {
        Throwable e = null;
        try {
            return _get.invoke(javaObject, JavaConcept.NOPARAM);
        } catch (IllegalAccessException e1) {
            e = e1;
            // should not happen
        } catch (IllegalArgumentException e2) {
            e = e2;
            // should not happen
        } catch (InvocationTargetException e3) {
            e = e3.getTargetException();
        }


        //throw new RuntimeException("Exception during feature extraction:");
        //System.out.pprintln("Exception during feature extraction:\n"+e);
        return e; //null;
    }

    @Override
    boolean canSet() {
        return _set != null;
    }

    @Override
    void setObjectValue(Object javaObject, Object value) {
        if (_set == null) {
            // no set method, just check existing value:
            //if (!Null.equals(getObjectValue(javaObject),value))
            String msg = "Cannot set attribute of objects of " + javaObject.getClass().getName()
                + ": No set method for\n" + _get;
            LOGGER.error(msg);
            throw new RuntimeException(msg);
            //return;
        }
        try {
            _set.invoke(javaObject, new Object[] { value });
            return;
        } catch (IllegalAccessException e1) {
            // should not happen
        } catch (IllegalArgumentException e2) {
            // should not happen
        } catch (InvocationTargetException e3) {
            // do nothing
        }

        //System.out.pprintln("Exception during feature setting:\n"+e);
        return;


        //throw new RuntimeException("Exception during feature setting:");
    }
}