package templates

import scala.xml.Node

abstract class RegiAmendTradeTemplate(source: Node) extends PartyTemplate(source) {
  protected[this] def templateTrade: Node

  def template: Node = {
    <fpml:nonpublicExecutionReport xmlns:fpml="http://www.fpml.org/FpML-5/recordkeeping"
                                   xmlns:fpmlext="http://www.fpml.org/FpML-5/ext" xmlns:rtsrep="http://www.fpml.ru/repository"
                                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" fpmlVersion="5-7">
      <fpml:header>
        <fpml:messageId>{ get(source \ "header" \"messageId") }</fpml:messageId>
        <fpml:sentBy>{ get(source \ "header" \ "sentBy") }</fpml:sentBy>
        <fpml:sendTo>{ get(source \ "header" \ "sendTo") }</fpml:sendTo>
        <fpml:creationTimestamp>{ get(source \ "header" \ "creationTimestamp") }</fpml:creationTimestamp>
        <fpml:implementationSpecification>
          <fpml:version>2</fpml:version>
        </fpml:implementationSpecification>
      </fpml:header>
      <fpml:isCorrection>{ get(source \ "isCorrection") }</fpml:isCorrection>
      <fpml:correlationId correlationIdScheme="">{ get(source \ "correlationId") }</fpml:correlationId>
      { if ((source \ "amendment").isEmpty) templateTrade
        else
          <fpml:amendment>
            { templateTrade }
            <fpml:agreementDate>{ get(source \ "amendment" \ "agreementDate") }</fpml:agreementDate>
            <fpml:effectiveDate>{ get(source \ "amendment" \ "effectiveDate") }</fpml:effectiveDate>
          </fpml:amendment>
      }
      { /* Uses dictionary from PartyTemplate for identifier */ }
      { for { s <- source \ "party"
              id = get(s, "id").mkString
              if id != "Sender" && id != "UTIGeneratingParty" } yield {
          <fpml:party id={ parties(id)._1 }>
            <fpml:partyId partyIdScheme={ parties(id)._2 }>{ parties(id)._1 }</fpml:partyId>
            <fpml:partyName>{ get(s \ "partyName") }</fpml:partyName>
            <fpml:country>{ get(s \ "country") }</fpml:country>
            <fpml:organizationType>{ get(s \ "classification") }</fpml:organizationType>
          </fpml:party>
        }
      }
      { for { s <- source \\ "trade" \ "nsdSpecificTradeFields" \ "clientDetails"
              id = get(s \ "id").mkString
              if id != msgNotFound } yield {
          <fpml:party id={ parties(id)._1 }>
            <fpml:partyId partyIdScheme={ parties(id)._2 }>{ parties(id)._1 }</fpml:partyId>
            <fpml:partyName>{ get(s \ "name") }</fpml:partyName>
            <fpml:country>{ get(s \ "country") }</fpml:country>
            <fpml:organizationType>{ get(s \ "classification") }</fpml:organizationType>
          </fpml:party>
        }
      }
    </fpml:nonpublicExecutionReport>
  }
}
