/*
   Copyright 2010 Aaron J. Radke

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package cc.drx

object Graph{
   def apply[V,E]() = new Graph[V,E]()
   def apply[V,E](a:V,b:V,e:E) = new Graph[V,E]().add(a,b,e)
   def apply[V,E](es:Seq[(V,V,E)]) = new Graph[V,E]() ++ es
}
class Graph[V,E](vs:Map[V,Map[V,E]]=Map[V,Map[V,E]]()){
   override def toString = (for((a,b,e) <- edges) yield f"$a to $b: $e") mkString "\n"

   def vertices = vs.keys
   def edges = for((a,es) <- vs.iterator; (b,e) <- es) yield (a,b,e)
   def edge(a:V,b:V):Option[E] = (vs get a) flatMap (_ get b)
   def vertices(a:V):Iterable[V] = (vs get a).toList flatMap (_.keys)


   private def addEdge(g:Map[V,Map[V,E]], a:V, b:V, e:E) = {
      val es = g.getOrElse(a,Map[V,E]()) //current edges: empty if non-exisitent
      val esWithB = es + (b -> e)         //add b to the edges, overwrite if already there
      g + (a -> esWithB)   //override list of edges
   }

   def +(a:V):Graph[V,E] = add(a)
   def add(a:V):Graph[V,E] = if(vs contains a) this else new Graph[V,E](vs + (a -> Map[V,E]()))
   def add(a:V, b:V, e:E):Graph[V,E] = new Graph(addEdge(vs,a,b,e))
   def add(a:V, b:V)(implicit f:(V,V) => E):Graph[V,E] = this.add( a, b, f(a,b) )

   def ++(es:Seq[(V,V,E)]):Graph[V,E] = new Graph(
     es.foldLeft(vs){case (g,(a,b,e)) => addEdge(g,a,b,e)}
   )
}