package pl.edu.pw.mini.jk.sg.chkconfig

import argonaut.Parse
import better.files.FileOps
import pl.edu.pw.mini.jk.sg.game.configuration.StaticGameConfigurationReader
import pl.edu.pw.mini.jk.sg.gteval.MethodConfigDecoder
import pl.edu.pw.mini.sg.se.{DefaultMethods, StrategyMethodParser}
import scalaz.{Failure, Success}

object ChkConfig {
  def main(args: Array[String]) : Unit = {
    val options = new CmdOptions(args)

    val gamePlugins = pl.edu.pw.mini.sg.game.deterministic.Plugins.defaultPlugins

    options.legacyGameConfigs.toOption.foreach(l =>
      l.foreach(file => {
        StaticGameConfigurationReader.readAagcFromFile(file)
	System.out.println(file + "OK")
      })
    )

    options.mixeductConfigs.foreach(l =>
      l.foreach(file => {
        MethodConfigDecoder.fromFile(file)
	System.out.println(file + " OK")
      })
    )

    options.deterministicGameConfigs.foreach(l =>
      l.map(_.toScala).foreach(file => {
        for {
          ext <- file.extension.toRight("File must have an extension")
          plugin <- gamePlugins.find("."+_.fileExtension ==  ext).toRight(s"No plugin for game extension $ext")
        } yield (Parse.decodeWith[Either[String, plugin.GameConfig], plugin.GameConfig](
          file.contentAsString, Right.apply, err => Left(err), (err, cur) => Left(s"$err, $cur")
        )(plugin.configJsonDecode)) match {
          case Right(c) => if(options.verbose()) Console.println(s"$file OK")
          case Left(err) => Console.println(s"$file ERROR: $err")
        }
      })
    )

    options.uasConfigs.foreach(l => l.map(_.toScala).foreach(file => {
      Parse.parse(file.contentAsString) match {
        case Right(json) => StrategyMethodParser.tryParse(DefaultMethods.list)(json) match {
          case Success(_) => if(options.verbose()) Console.println(s"$file OK")
          case Failure(errorList) => Console.println(s"$file ERROR: ${errorList.stream.mkString("\n")}")
        }
        case Left(err) => Console.println(s"$file ERROR: $err")
      }
    }))
  }
}
