/*
 * @author Ranides Atterwim {@literal <ranides@gmail.com>}
 * @copyright Ranides Atterwim
 * @license WTFPL
 * @url http://ranides.net/projects/assira
 */

package net.ranides.assira.reflection.impl.bean;

import net.ranides.assira.reflection.*;

import java.io.Serializable;

/**
 * Default implementation of ordinary BeanProperty
 * Delegates read/write operations to getter and setter methods.
 *
 * @author Ranides Atterwim {@literal <ranides@gmail.com>}
 */
public class RPField extends ABeanProperty implements Serializable {

    private static final long serialVersionUID = 3L;
    
    private final IMethod setter;
    private final IMethod getter;

    RPField(RBeanPropertyBuilder info) {
        super(info.type(), info.name());
        this.getter = info.vgetter();
        this.setter = info.vsetter();
    }
    
    @Override
    public void set(Object that, Object value) {
        if(null == setter) {
            throw FBeanModel.newUnsupportedOperationException("Property " + name() + " is read-only");
        }
        setter.invoke(that, value);
    }

    @Override
    public Object get(Object that) {
        if(null == getter) {
            throw FBeanModel.newUnsupportedOperationException("Property " + name() + " is write-only");
        }
        return getter.invoke(that);
    }

    @Override
    public boolean isReadable() {
        return getter != null;
    }

    @Override
    public boolean isWritable() {
        return setter != null;
    }

    @Override
    public IClass<?> parent() {
        if(getter != null) {
            return getter.parent();
        }
        if(setter != null) {
            return setter.parent();
        }
        return IClass.NULL;
    }
}
