package pl.edu.pw.mini.sg.graphviz
import org.rogach.scallop.ScallopConf
import java.io.{File => JFile}

import scala.collection.JavaConverters._
import pl.edu.pw.mini.jk.sg.game.configuration.StaticGameConfigurationReader
import better.files.File


object App2 {
  final class Options(args: Seq[String]) extends ScallopConf(args) {
    val game = opt[String](name = "game", short='g', required=true).map(x => new JFile(x))
    val output = opt[String](name = "output", short='o', required = true).map(x => File(x))
    val positionInfo = opt[String](name = "positionInfo", short='p', required = false).map(x => new JFile(x))

    verify()
  }

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

    def payoffTransform(x: Double) = (x+30.0)/60.0

    val positions = options.positionInfo.toOption.map(App.readPositionInfo _).map(_.asScala)
    val sgc = StaticGameConfigurationReader.readAagcFromFile(options.game()).getStaticGameConfiguration()
    def getPosition(vertex: Int) : Option[(Double, Double)] = positions.flatMap(p => p.find(_.id==vertex))
      .map(p => (p.x*110, p.y*(-85)))

    val vertices : List[AbstractVertex] = Range(0, sgc.getGraphDescription().vertexCount).map(v =>
      if(v == 0)
        new DefenderStartVertex(v.toString, payoffTransform(sgc.getVertexDefenderReward(v, 0)), payoffTransform(sgc.getVertexAttackerPenalty(v, 0)), getPosition(v))
      else if(sgc.getSpawns().contains(v))
        new StartVertex(v.toString, payoffTransform(sgc.getVertexDefenderReward(v, 0)), payoffTransform(sgc.getVertexAttackerPenalty(v, 0)), getPosition(v))
      else if(sgc.getTargets().contains(v)) {
        val targetId = sgc.getTargets().indexOf(v)
        new TargetVertex(
          v.toString,
          payoffTransform(sgc.getVertexDefenderReward(v, 0)), payoffTransform(sgc.getVertexAttackerPenalty(v, 0)),
          payoffTransform(sgc.getDefenderPenalty(targetId, 0)), payoffTransform(sgc.getAttackerReward(targetId, 0)),
          getPosition(v)
        )
      } else
        new RegularVertex(v.toString, payoffTransform(sgc.getVertexDefenderReward(v, 0)), payoffTransform(sgc.getVertexAttackerPenalty(v, 0)), getPosition(v))
    ).toList
    val edges = sgc.getGraphDescription().edges.filter(e => e.from < e.to)

    options.output().printWriter().apply(pw => {
      pw.println("graph G{nodesep=0.2;ranksep=0.3;")
      vertices.foreach(v => pw.println(v.draw))
      edges.foreach(e => pw.println(s"${e.from}--${e.to};"))
      pw.println("}")
    })
  }
}
