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

import java.io.File

import scala.io.Source

import argonaut.{DecodeJson, Parse}

class ConfigParseException(msg: String) extends RuntimeException(msg)

class SimpleGamePlugin[C](
  val fileNameMatcher: String => Boolean,
  val fileParser: File => Either[String, C],
  val gameVariantRunnerConstructor: C => GameVariantRunner
) extends GamePlugin {
  override def fileToGameVariantRunner(file: File): GameVariantRunner = {
    fileParser(file) match {
      case Left(error) => throw new ConfigParseException(error)
      case Right(config) => gameVariantRunnerConstructor(config)
    }
  }
  override def matchFile(file: File): Boolean = fileNameMatcher(file.toString())

  override def fileToGameVariantRunner(file: File, transformer: File): GameVariantRunner = {
    throw new IllegalArgumentException("This game does not support transformers")
  }
}

object SimpleGamePlugin {
  def fileParserFromJson[C](decoder: DecodeJson[C]) : (File => Either[String, C])  = file => {
    val contents = Source.fromFile(file).mkString
    Parse.parse(contents).right.map(json => 
      json.as(decoder).toEither.left.map(_.toString)
    ) match {
      case Right(c) => c
      case Left(error) => throw new ConfigParseException(error)
    }
  }
}
