package pl.edu.pw.mini.jk.sg.mixeduct.transfer.transformers
import pl.edu.pw.mini.jk.sg.uct.tree.PayoffTransformer
import pl.edu.pw.mini.jk.sg.uct.tree.UctNode
import pl.edu.pw.mini.jk.sg.uct.tree.UnmodifiableDecisionStatisticsView
import pl.edu.pw.mini.jk.sg.uct.UCTDecisionStatistics

object NormalizeTransformer extends PayoffTransformer {
  override type NodeStat = Unit
  override type GlobalStat = (Double, Double)

  override def calculateNodeStat(node: UctNode[_, _]): NodeStat = ()
  override def calculateGlobalStat(
      stat: => Iterable[UnmodifiableDecisionStatisticsView]
  ): (Double, Double) = stat.foldLeft((Double.PositiveInfinity, Double.NegativeInfinity)) {
    case ((min, max), stat) =>
      (Math.min(min, stat.averagePayoff), Math.max(max, stat.averagePayoff))
  }
  override def transformStatistics(
      stat: UnmodifiableDecisionStatisticsView,
      nodeStat: Unit,
      globalStat: (Double, Double)
  ): UCTDecisionStatistics =
    new UCTDecisionStatistics(
      stat.visitsCount,
      stat.realVisitsCount,
      if(globalStat._1 < globalStat._2)  (stat.averagePayoff - globalStat._1) / (globalStat._2 - globalStat._1)
      else 0
    )
}
