package pl.edu.pw.mini.sg.matrix

import argonaut.{ CodecJson, DecodeJson, DecodeResult, EncodeJson, HCursor }
import java.util.UUID


object MatrixGameConfigJson {
  val ID_FIELD = "id"
  val DEFENDER_MATRIX_FIELD = "defenderMatrix"
  val ATTACKER_MATRIX_FIELD = "attackerMatrix"

  private case class NotVerifiedMGC(id: UUID, defenderMatrix: Vector[Vector[Double]], attackerMatrix: Vector[Vector[Double]])

  private val nvmgcDecodeJson: CodecJson[NotVerifiedMGC] = CodecJson.casecodec3(NotVerifiedMGC.apply, NotVerifiedMGC.unapply)(ID_FIELD, DEFENDER_MATRIX_FIELD, ATTACKER_MATRIX_FIELD)

  implicit val matrixGameConfigDecodeJson : DecodeJson[MatrixGameConfig] =
    DecodeJson { hc: HCursor =>
      nvmgcDecodeJson.decode(hc).flatMap { case NotVerifiedMGC(id, dm, am) =>
        MatrixGameConfig.verifyMarices(dm, am) match {
          case Right(_) => DecodeResult.ok(MatrixGameConfig(id, dm, am))
          case Left(error) => DecodeResult.fail(error, hc.history)
        }
      }
    }


  implicit val matrixGameConfigEncodeJson : EncodeJson[MatrixGameConfig] =
    EncodeJson.jencode3L((MatrixGameConfig.unapply _).andThen(_.get))(
      ID_FIELD, DEFENDER_MATRIX_FIELD, ATTACKER_MATRIX_FIELD)
}
