package de.dhbwstuttgart.target.generate;

import de.dhbwstuttgart.syntaxtree.type.TypePlaceholder;
import de.dhbwstuttgart.typeinference.result.PairTPHequalRefTypeOrWildcardType;
import de.dhbwstuttgart.typeinference.result.PairTPHsmallerTPH;
import de.dhbwstuttgart.typeinference.result.ResultPair;

import java.util.*;

public class GenericsResultSet extends AbstractSet<GenerateGenerics.Pair> {

    final Set<GenerateGenerics.Pair> backing;
    final Map<TypePlaceholder, TypePlaceholder> equality;

    public GenericsResultSet(Set<GenerateGenerics.Pair> backing, Map<TypePlaceholder, TypePlaceholder> equality) {
        this.backing = backing == null ? new HashSet<>() : new HashSet<>(backing);
        this.equality = equality;
    }

    @Override
    public Iterator<GenerateGenerics.Pair> iterator() {
        return backing.iterator();
    }

    @Override
    public int size() {
        return backing.size();
    }

    public Optional<ResultPair<?, ?>> getResultPairFor(TypePlaceholder tph) {
        var tph2 = equality.getOrDefault(tph, tph);
        return this.stream().filter(pair -> {
            return pair.left.resolve().equals(tph2);
        }).findFirst().map(pair -> {
            ResultPair<?, ?> res = null;
            if (pair instanceof GenerateGenerics.PairLT lt)
                res = new PairTPHsmallerTPH(lt.left.resolve(), lt.right.resolve());
            else if (pair instanceof GenerateGenerics.PairEQ eq)
                res = new PairTPHequalRefTypeOrWildcardType(eq.left.resolve(), eq.right);
            return res;
        });
    }
}
