package cc.smtweb.framework.core.mvc.controller.access;

import cc.smtweb.framework.core.exception.BindBeanException;
import cc.smtweb.framework.core.mvc.controller.IBeanContext;

import java.lang.reflect.Field;
import java.util.Map;

public abstract class FieldAccess {
    protected final Field field;

    public FieldAccess(Field field) {
        this.field = field;
    }

    protected abstract Object getFieldValue(Object instance, IBeanContext context, Map<String, Object> params);

    public boolean writeValue(Object instance, IBeanContext context, Map<String, Object> params) {
        Object bean = getFieldValue(instance, context, params);

        if (bean != null) {
            field.setAccessible(true);

            try {
                field.set(instance, bean);
            } catch (IllegalArgumentException | IllegalAccessException e) {
                throw new BindBeanException("not set " + getFullName(instance) + " value", e);
            }

            return true;
        }

        return false;
    }

    public String getFullName(Object instance) {
        return instance.getClass().getName() + "." + field.getName();
    }
}
