/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.dhaval.meta.extractor;

import com.dhaval.meta.MetaField;
import com.dhaval.meta.MetaType;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author dhaval
 */
public class MetaExtractor {

    public MetaExtractor(){

    }

    public List<MetaResult> extract(Class cls){
        return _extract("", cls);
    }

    public List<MetaResult> _extract(String header, Class cls){
        List<MetaResult> resultSet = new ArrayList<MetaResult>();

        Field[] fields = cls.getDeclaredFields();
//        System.out.println(fields.length + " fields found in class " + cls.getName());
        for(Field field : fields){
            Annotation[] fieldAnnotations = field.getDeclaredAnnotations();
//            System.out.println(fieldAnnotations.length + " annotations found on field " + field.getName());
            for (Annotation annotation : fieldAnnotations) {
                if(annotation.annotationType() == MetaField.class){
                    MetaField metaField = (MetaField) annotation;
                    MetaResult result =new MetaResult();
                    if(header == null || header.length() <= 0){
                        result.setFieldName(metaField.name());
                    }else{
                        result.setFieldName(header + "." + metaField.name());
                    }
                    result.setDisplayName(metaField.displayName());

                    resultSet.add(result);
                }else if(annotation.annotationType() == MetaType.class){
//                    System.out.println(field.getName() + " is another type " + field.getType());
                    MetaType metaType = (MetaType) annotation;
                    resultSet.addAll(_extract(metaType.name(), field.getType()));
                }
            }
        }
        return resultSet;
    }
}
