/*
   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

/**Topological sorting result of hopefully graphs (preferably DAG's but report cycles) */
class TSort[T](val sorted:Iterable[T], val cyclic:Iterable[(T,T)]){
  def isDAG:Boolean = cyclic.isEmpty
  override def toString = {
    val sortList = sorted.mkString(", ")
    val cyclicList = cyclic.map{case (a,b) => s"$a -> $b"}.mkString(", ")
    s"TSort(sorted=List($sortList), cyclic=List($cyclicList))"
  }
}
object TSort{
  def edges[T](edges:Iterable[(T,T)]):TSort[T] = {
    val deps = edges.groupBy(_._1).map{case (k,vs) => k -> vs.map{_._2}.toSet}
    apply(deps)
  }
  def apply[T](deps:Map[T,Iterable[T]]):TSort[T] = {
    val nodes = deps.keys ++ deps.values.flatten
    def findDeps(node:T):Iterable[T] = deps.getOrElse(node, List.empty[T])
    apply(deps.keys, findDeps)
  }
  //a ghost of https://www.scala-sbt.org/0.13.12/sxr/sbt/Dag.scala.html
  def apply[T](nodes: Iterable[T], deps: T => Iterable[T]): TSort[T] = {
    import scala.collection.mutable
    val discovered = mutable.HashSet.empty[T]  //order not important, (and still provides consistent sort results if T is a consistent hash)
    val finished =  mutable.LinkedHashSet.empty[T] //preserve insertion order
    val cyclic =  mutable.LinkedHashSet.empty[(T,T)]  //preserve insertion order

    def visit(node: T, from:Option[T]): Unit = {
      if (!discovered(node)) {
        discovered(node) = true
        visitAll(deps(node), Some(node))
        finished += node
      } else if (!finished(node)){
        if(from.isDefined) cyclic += node -> from.get //TODO make sure all cyclic nodes are captured even if from is not defined
        else cyclic += node -> node //FIXME is this really needed here? 
        // println(s"Warning: cyclic node: $node from:$from")
      }
      ()
    }
    def visitAll(nodes: Iterable[T], from:Option[T]) = nodes.foreach{node => visit(node, from)}

    visitAll(nodes, None)

    new TSort(finished.toList, cyclic.toList)
  }

}