package turin.relations;


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

public class ManyToManyRelation<A, B> implements Relation<A,B> {

    private Map<A, List<B>> byEndpointA = new HashMap<>();
    private Map<B, List<A>> byEndpointB = new HashMap<>();

    @Override
    public void link(A endpointA, B endpointB) {
        if (areLinked(endpointA, endpointB)) {
            return;
        }
        if (!byEndpointA.containsKey(endpointA)) {
            byEndpointA.put(endpointA, new LinkedList<B>());
        }
        if (!byEndpointB.containsKey(endpointB)) {
            byEndpointB.put(endpointB, new LinkedList<A>());
        }
        byEndpointA.get(endpointA).add(endpointB);
        byEndpointB.get(endpointB).add(endpointA);
    }

    @Override
    public void unlink(Object professor, Object course) {
        byEndpointA.get(professor).remove(course);
        byEndpointB.get(course).remove(professor);
    }

    @Override
    public boolean areLinked(Object a, Object b) {
        if (byEndpointB.containsKey(b)) {
            return byEndpointB.get(b).contains(a);
        } else {
            return false;
        }
    }

    public ReferenceMultipleEndpoint getReferenceForB(B b) {
        return new ReferenceMultipleEndpoint(b, byEndpointB, this);
    }

    public ReferenceMultipleEndpoint getReferenceForA(A a) {
        return new ReferenceMultipleEndpoint(a, byEndpointA, this);
    }

}
@@ -305,16 +305,264 @@
 ap%3C%3E();%0A
+    private Map%3CA, Subset%3E aSubsets = new HashMap%3C%3E();%0A    private Map%3CB, Subset%3E bSubsets = new HashMap%3C%3E();%0A%0A    public Subset newASubset() %7B%0A        return new Subset();%0A    %7D%0A    public Subset newBSubset() %7B%0A        return new Subset();%0A    %7D%0A%0A
 %0A    @Ov
@@ -1718,9 +1718,346 @@
 %0A    %7D%0A%0A
+    public ReferenceMultipleEndpoint getReferenceForA(A a, Subset subset) %7B%0A        return new ReferenceMultipleEndpoint(a, byEndpointA, this, bSubsets, subset);%0A    %7D%0A%0A    public ReferenceMultipleEndpoint getReferenceForB(B b, Subset subset) %7B%0A        return new ReferenceMultipleEndpoint(b, byEndpointB, this, aSubsets, subset);%0A    %7D%0A
 %7D

implement subsets also for the Many to Many relations