package pl.edu.pw.mini.jk.sg.uct.tree.export
import scodec.Codec
import java.nio.charset.Charset
import shapeless.Generic

final case class ExportUctTree[+S, M](
  state: S,
  successors: Map[M, (ExportStatistics, ExportUctTree[S, M])]
) {
  def bimap[SS, MM](fm: M => MM, fs: S => SS) : ExportUctTree[SS, MM] =
    ExportUctTree(fs(state),
      successors.map{case (m, (st, succ)) => (fm(m), (st, succ.bimap(fm, fs)))}.toMap)
}

object ExportUctTree {
  import scodec.codecs._

  val esCodec : Codec[ExportStatistics] = (int32L ~ int32L ~ doubleL).flattenLeftPairs.as[ExportStatistics]
  def mapCodec[K,V](implicit kc: Codec[K], vc: Codec[V]) : Codec[Map[K,V]] = lazily(listOfN(int32L, kc ~ vc)).xmap(_.toMap, _.toList)
  def codec: Codec[ExportUctTree[String, String]] = {
    implicit val cd = Charset.forName("UTF-8")
    scodec.codecs.lazily(string32L ~ mapCodec(string32L, esCodec ~ codec)).flattenLeftPairs.as[ExportUctTree[String, String]]
  }
}
