/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package graph.graphlexis;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 *
 * @author martin
 */
public class Graphlexis {
    private Set<Link> lnks;

    public Graphlexis() {
        this.lnks = new HashSet<>();
    }

    public boolean addLink(Object first, Object second){
        if (first==null || second==null || first==second || first.equals(second))
            return false;
        Link lnkA = new Link(first,second),
             lnkB = new Link(second,first);
        if (lnks.contains(first)|| lnks.contains(second))
            return false;
        return lnks.add(lnkA);
    }
    
    public Set<Object> neighbor(Object node){
        Set<Object> found = new HashSet<>();
        for (Link lnk : lnks)
            if (lnk.first.equals(node))
                found.add(lnk.second);
            else if (lnk.second.equals(node))
                found.add(lnk.first);
        return found;
    }
    
    public void removeNode(Object node){
        List<Object> tmp = new ArrayList<>();
        for (Link lnk : lnks)
            if (lnk.first.equals(node))
                tmp.add(lnk);
            else if (lnk.second.equals(node))
                tmp.add(lnk);
        lnks.removeAll(tmp);
    }
    
    public static class Link{
        private final Object first,second;

        public Link(Object first, Object second) {
            this.first = first;
            this.second = second;
        }

        public Object getFirst() {
            return first;
        }

        public Object getSecond() {
            return second;
        }

        @Override
        public int hashCode() {
            int hash = 7;
            hash = 37 * hash + Objects.hashCode(this.first);
            hash = 37 * hash + Objects.hashCode(this.second);
            return hash;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final Link other = (Link) obj;
            if (!Objects.equals(this.first, other.first)) {
                return false;
            }
            if (!Objects.equals(this.second, other.second)) {
                return false;
            }
            return true;
        }
        
    }
}
