



package hu.elte.inf.pszt.prt.javalib.utils;

import hu.elte.inf.pszt.prt.javalib.db.jpa.ColumnLabel;
import hu.elte.inf.pszt.prt.javalib.db.jpa.EntityWithID;
import java.lang.reflect.InvocationTargetException;

/**
 *
 * @author trust56
 */
public class EntityUtils {

    public static <GenericEntity extends EntityWithID> Object invokeGetter(GenericEntity entity, int attributeIndex) {
        String attributeName = entity.getClass().getDeclaredFields()[attributeIndex + 2].getName();
        String getterMethodName = "get" + attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1);
        try {
            return entity.getClass().getMethod(getterMethodName).invoke(entity);
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
            getterMethodName = "is" + attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1);
            try {
                return entity.getClass().getMethod(getterMethodName).invoke(entity);
            } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex2) {
                return ex2.getMessage();
            }
        }
    }
    
    public static <GenericEntity extends EntityWithID> String getColumnLabel(Class<GenericEntity> claas, int attributeIndex){
//        System.out.println(claas.getName());
//        System.out.println(attributeIndex);
        ColumnLabel columnAnnotation = claas.getDeclaredFields()[attributeIndex + 2].getAnnotation(ColumnLabel.class);
        if (columnAnnotation == null) {
            return null;
        } else {
            return columnAnnotation.label();
        }
    }
}
