package in.cdac.medinfo.csnotk.csnolib.ecl.constraint;

import org.snomed.langauges.ecl.domain.refinement.EclAttributeSet;
import org.snomed.langauges.ecl.domain.refinement.SubAttributeSet;
//Changes
import in.cdac.medinfo.csnotk.csnolib.model.Concept;
import java.util.Set;
import java.util.List;
import java.util.Collection;
import com.google.common.collect.Sets;
import static com.google.common.collect.Sets.newHashSet;
import static java.util.stream.Collectors.toSet;

public class SEclAttributeSet extends EclAttributeSet implements SConstraint {

    @Override
    public Set<Concept> addQuery() {
        Set<Concept> finalSctIds = null;
        if (getDisjunctionAttributeSet() != null) {
            finalSctIds = ((SConstraint) getSubAttributeSet()).addQuery();
            for (SubAttributeSet attributeSet : getDisjunctionAttributeSet()) {
                finalSctIds = Sets.union( finalSctIds,((SConstraint) attributeSet).addQuery());
            }
        } else {
            finalSctIds = ((SConstraint) getSubAttributeSet()).addQuery();
            if (getConjunctionAttributeSet() != null) {
                for (SubAttributeSet attributeSet : getConjunctionAttributeSet()) {
                    finalSctIds = Sets.intersection( finalSctIds,((SConstraint) attributeSet).addQuery());
                }
            }
        }
        return finalSctIds;
    }

    @Override
    public Set<String> getConceptIds() {
        Set<String> conceptIds = newHashSet(((SSubAttributeSet) subAttributeSet).getConceptIds());
        if ((conjunctionAttributeSet != null) && !conjunctionAttributeSet.isEmpty()) {
            conceptIds.addAll(getConceptIds(conjunctionAttributeSet));
        }
        if ((disjunctionAttributeSet != null) && !disjunctionAttributeSet.isEmpty()) {
            conceptIds.addAll(getConceptIds(disjunctionAttributeSet));
        }
        return conceptIds;
    }

    private Collection<? extends String> getConceptIds(List<SubAttributeSet> subAttributeSets) {
        return subAttributeSets.stream()
                .map(SSubAttributeSet.class::cast)
                .map(SSubAttributeSet::getConceptIds)
                .flatMap(Set::stream)
                .collect(toSet());
    }
}
