package eu.eudat.logic.services.forms;

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

import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

/**
 * Created by ikalyvas on 3/5/2018.
 */
public class VisibilityContext {
    private List<VisibilityRule> visibilityRules = new LinkedList<>();

    public List<VisibilityRule> getVisibilityRules() {
        return visibilityRules;
    }

    public VisibilityRule get(String id) {
        Optional<VisibilityRule> rule = visibilityRules.stream().filter(item -> item.getVisibilityRuleTargetId().equals(id)).findFirst();
        if (rule.isPresent()) return rule.get();
        return null;
    }

    public void buildVisibilityContext(List<Rule> sources) {
        sources.forEach(this::addToVisibilityRulesContext);
    }

    private void addToVisibilityRulesContext(Rule item) {
        VisibilityRuleSource source = new VisibilityRuleSource();
        source.setVisibilityRuleSourceId(item.getSourceField());
        source.setVisibilityRuleSourceValue(item.getRequiredValue());

        Optional<VisibilityRule> visibilityRuleOptional = visibilityRules.stream().filter(rule -> rule.getVisibilityRuleTargetId().equals(item.getTargetField())).findFirst();
        if (visibilityRuleOptional.isPresent()) visibilityRuleOptional.get().getVisibilityRuleSources().add(source);
        else {
            List<VisibilityRuleSource> sources = new LinkedList<>();
            sources.add(source);
            VisibilityRule visibilityRule = new VisibilityRule();
            visibilityRule.setVisibilityRuleTargetId(item.getTargetField());
            visibilityRule.setVisibilityRuleSources(sources);
            this.visibilityRules.add(visibilityRule);
        }
    }
}
