package eu.eudat.logic.services.forms;

import eu.eudat.models.data.user.components.commons.Rule;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ikalyvas on 3/5/2018.
 */
@Service("visibilityRuleService")
public class VisibilityRuleServiceImpl implements VisibilityRuleService {
    private Map<String, Boolean> elementVisibility = new HashMap<>();
    private VisibilityContext visibilityContext;
    private Map<String, Object> properties;

    public Boolean isElementVisible(String id) {
        if (!this.elementVisibility.containsKey(id) || this.elementVisibility.get(id)) return true;
        return false;
    }

    public void setProperties(Map<String, Object> properties) {
        this.properties = properties;
    }

    public void buildVisibilityContext(List<Rule> sources) {
        this.visibilityContext = new VisibilityContext();
        this.visibilityContext.buildVisibilityContext(sources);
        this.visibilityContext.getVisibilityRules().forEach(item-> this.evaluateVisibility(item));
    }

    private void evaluateVisibility(VisibilityRule rule) {
        List<VisibilityRuleSource> sources = rule.getVisibilityRuleSources();
        for(int i = 0; i < sources.size(); i++){
            if (!properties.containsKey(sources.get(i).getVisibilityRuleSourceId()) || !properties.get(sources.get(i).getVisibilityRuleSourceId()).equals(sources.get(i).getVisibilityRuleSourceValue())) {
                this.elementVisibility.put(rule.getVisibilityRuleTargetId(), false);
                return;
            }else{
                this.elementVisibility.put(rule.getVisibilityRuleTargetId(), true);
            }
        }
    }
}
