package eu.eudat.logic.utilities.helpers;

import eu.eudat.models.data.user.components.commons.Rule;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

public class ModelBuilderCollector {


    /**
     * @param sections
     * @return
     */
    public static List<Rule> collectRules(List<eu.eudat.models.data.entities.xmlmodels.datasetprofiledefinition.Section> sections) {
        List<Rule> rules = new LinkedList();
        for (eu.eudat.models.data.entities.xmlmodels.datasetprofiledefinition.Section section : sections) {
            if (!section.getSections().isEmpty()) {
                rules.addAll(collectRules(section.getSections()));
            }
            rules.addAll(
                    section.getFieldSets().stream()
                            .map(fieldset -> fieldset.getFields())
                            .flatMap(List::stream)
                            .map(field -> getRulesFromField(field.getId(), field.getVisible()
                                    .getRules()))
                            .flatMap(List::stream)
                            .collect(Collectors.toList()));
        }

        return rules;
    }

    private static List<Rule> getRulesFromField(String id, List<eu.eudat.models.data.components.commons.Rule> rules) {
        List<Rule> modelRules = new LinkedList();
        for (eu.eudat.models.data.components.commons.Rule rule : rules) {
            Rule modelRule = new Rule().fromDefinitionRule(rule);
            modelRule.setSourceField(id);
            modelRules.add(modelRule);
        }
        return modelRules;
    }

}
