package pl.edu.pw.mini.sg.movingtargets.multi

import canes.game.{ AllUnitsPositions, PureDefenderStrategy }
import scala.collection.JavaConverters._

import pl.edu.pw.mini.jk.sg.game.NormalizableFactory
import pl.edu.pw.mini.sg.movingtargets.{AttackerDecision, MovingTargetsGameConfig}
import pl.edu.pw.mini.sg.movingtargets.helpers.FactoryWithJsonOutput

case class MovingTargetsMultiMutableGameFactory(gameConfig: MovingTargetsGameConfig)
  extends NormalizableFactory[AttackerDecision, MovingTargetsDefenderMoveMulti, MovingTargetsMultiMutableGame] with FactoryWithJsonOutput[MovingTargetsDefenderMoveMulti] {
  val immutableGame: MovingTargetsMultiImmutableGame = MovingTargetsMultiImmutableGame.initialState(gameConfig)

  override def create(): MovingTargetsMultiMutableGame = new MovingTargetsMultiMutableGame(immutableGame, immutableGame, Nil, 0, 0)
  override def denormalize(): this.type = this
  override def normalize(): this.type = this

  override def convertPureStrategy(seq: java.util.List[MovingTargetsDefenderMoveMulti]): PureDefenderStrategy = PureDefenderStrategy(
    MovingTargetsMultiMutableGameFactory.evenLengthSequences(gameConfig.defenderCount)(seq.asScala).map(v => AllUnitsPositions(v.map(m => gameConfig.toDoublePositions(m.position)).toList)).toVector
  )

}

object MovingTargetsMultiMutableGameFactory {
  def evenLengthSequences[T](len: Int)(seq: Seq[T]): Vector[Vector[T]] = {
    seq.foldLeft((Vector[Vector[T]](), Vector[T]())) {
      case ((l, v), el) =>
        if (v.length == len - 1) (l :+ (v :+ el), Vector())
        else (l, v :+ el)
    } match {
      case (l, Vector()) => l
      case _ => throw new IllegalArgumentException("Number of elements oin seq not dividable")
    }
  }
}
