package cc.smtweb.framework.core.db.dao;

import cc.smtweb.framework.core.db.impl.DefaultEntity;
import cc.smtweb.framework.core.db.vo.ModelField;
import cc.smtweb.framework.core.exception.DbException;
import lombok.Getter;

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

/**
 * 值对象字段处理类
 *
 * @author xkliu
 */
@Getter
public class EntityColumn {
    //非平台实体定义
    private String fieldName;
    private ModelField field;
    private final Method readMethod;
    private final Method writeMethod;

    /**
     * 构建值对象字段
     *
     * @param field       字段名
     * @param readMethod  读值方法
     * @param writeMethod 写值方法
     */
    public EntityColumn(ModelField field, Method readMethod, Method writeMethod) {
        this.field = field;
        this.readMethod = readMethod;
        this.writeMethod = writeMethod;
    }

    public EntityColumn(String fieldName, Method readMethod, Method writeMethod) {
        this.fieldName = fieldName;
        this.readMethod = readMethod;
        this.writeMethod = writeMethod;
    }

    /**
     * 从对象中读取字段对应的属性值
     *
     * @param obj 值对象
     * @return 属性值
     */
    public Object readValue(Object obj) {
        if (readMethod != null) {
            try {
                return readMethod.invoke(obj);
            } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
                throw new DbException(e);
            }
        } else {
            return ((DefaultEntity) obj).get(field.getName());
        }
    }

    /**
     * 写入值到对象字段对象属性
     *
     * @param obj   值对象
     * @param value 属性值
     */
    public void writeValue(Object obj, Object value) {
        if (readMethod != null) {
            try {
                writeMethod.invoke(obj, value);
            } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
                throw new DbException(e);
            }
        } else {
            ((DefaultEntity) obj).put(field.getName(), value);
        }
    }
}
