package com.ffii.core.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.springframework.beans.BeansException;

import com.ffii.core.entity.BaseEntity;

public class BeanUtils extends org.springframework.beans.BeanUtils {

    @SuppressWarnings("unchecked")
    public static void copyProperties(Object source, Object target) throws BeansException {
        boolean validId = false;
        Field idField = null;
        Method getIdMethod = null;

        try {
            idField = source.getClass().getDeclaredField("id");
            getIdMethod = source.getClass().getMethod("getId");

            validId = idField != null && getIdMethod != null && (Long) getIdMethod.invoke(source) > 0L;
        } catch (Exception e) {

        }

        if ((source instanceof BaseEntity && (((BaseEntity<Long>) source).getId() == null || ((BaseEntity<Long>) source).getId() <= 0L)) || !validId) {
            org.springframework.beans.BeanUtils.copyProperties(source, target, "id");
        } else {
            org.springframework.beans.BeanUtils.copyProperties(source, target);
        }
    }
}