import xmlvalid._
import scala.util.{Failure, Success, Try}
import scala.xml._
import templates._

object Main extends App {

  implicit def templateFactory(source: Node): Template with Logger= {
    (source \ "trade").head.child
    .filter {
      case v: Elem => true
      case _ => false
    }(1).label match {
      case "repo" => new RepoTemplate(source) with Logger
      case v => throw new Exception("Undefined trade type")
    }
  }

  val p = new PrettyPrinter(140, 2)
  val sourceXml = XML.loadFile("src/main/resources/nsd/Repo Client equity.xml")
  val template = Template(sourceXml)
  val outputXml = XML.loadString(p.format(template.render))
  //val outputXml = template.template

  //template.log()

  Try {
    XMLValid("src/main/resources/nsd/nsd-ext-merged-schema.xsd").loadString(sourceXml.mkString)
  } match {
    case Success(_) => println("Source xml success check against NSD schema")
    case Failure(ex) => println(s"Source xml isn`t wellformed or invalid: ${ex.getMessage}")
  }

  Try {
    XMLValid("src/main/resources/rts/fpml-recordkeeping-merged-schema.xsd").loadString(outputXml.mkString)
  } match {
    case Success(_) => println("Output xml success check against RTS schema")
    case Failure(ex) => println(s"Output xml isn`t wellformed or invalid: ${ex.getMessage}")
  }

  XML.save("output/Output repo RTS.xml", outputXml, xmlDecl = true)

}
