<commit_before>package sp.processSimulateImporter

import akka.actor._
import sp.domain.logic.{ActionParser, PropositionParser}
import sp.system._
import sp.system.messages._
import sp.domain._
import sp.domain.Logic._
import scala.concurrent.Future
import akka.util._
import akka.pattern.ask
import scala.concurrent._
import scala.concurrent.duration._
import akka.camel._

import scala.util._

/**
 * Some unclear interfaces. What is items?
 */

case class PSsetup(command: String, sops: List[ID])

object ProcessSimulateService extends SPService {
  val specification = SPAttributes(
    "service" -> SPAttributes(
      "group" -> "External",
      "description" -> "Pull/push data from/to Process Simulate"
    ),
    "setup" -> SPAttributes(
      "command" -> KeyDefinition("String", List("export seq", "import", "import_single", "update sim ids"), Some("export seq")),
      "sops" -> KeyDefinition("List[ID]", List(), Some(SPValue(List())))
    )
  )

  val transformTuple = (
    TransformValue("setup", _.getAs[PSsetup]("setup"))
    )
  val transformation = transformToList(transformTuple.productIterator.toList)

  def props(modelHandler: ActorRef, psAmq: ActorRef) = ServiceLauncher.props(Props(classOf[ProcessSimulateService], modelHandler, psAmq))
}

// activemq part    Beövs det inte en consumer också?
class ProcessSimulateAMQ extends Actor with Producer {
  implicit val timeout = Timeout(100 seconds)
  def endpointUri = "activemq:PS"
}

object ProcessSimulateAMQ {
  def props = Props(classOf[ProcessSimulateAMQ])
}

class ProcessSimulateService(modelHandler: ActorRef, psAmq: ActorRef) extends Actor with ServiceSupport {
  implicit val timeout = Timeout(100 seconds)

  import context.dispatcher

  def receive = {
    case r@Request(service, attr, ids, reqID) => {
      val replyTo = sender()
      implicit val rnr = RequestNReply(r, replyTo)
      val progress = context.actorOf(progressHandler)

      progress ! SPAttributes("progress" -> "creating a json for Process simulate")

      val setup = transform(ProcessSimulateService.transformTuple)
      val core = r.attributes.getAs[ServiceHandlerAttributes]("core").get

      val res = setup.command match {
        case "export seq" => exportSeq(core.model, ids, setup.sops, progress)
        case "import" => fetch(core.model, ids, progress)
        case "import_single" => fetch_single(core.model, ids, progress)
        case "update sim ids" => updateSimIds(ids, progress)
        case _ => throw new Exception("No such command! How to do this the scala way?")
      }

      res onComplete {
        case Success(resp) => {
          replyTo ! resp
          terminate(progress)
        }
        case Failure(t) => {
          replyTo ! SPError("Failed when communicating")
          terminate(progress)
        }
      }
    }
    case _ => sender ! SPError("Ill formed request");
  }

  def terminate(progress: ActorRef): Unit = {
    self ! PoisonPill
    progress ! PoisonPill
  }

  def createExportJsonHelper(sop : SOP, ids: List[IDAble], ack : SPAttributes) : SPAttributes = {
    sop match {
      case h: Hierarchy =>
        val ops = ids.find(o => o.id == h.operation)
        ack merge (ops match {
          case Some(o) => SPAttributes("name" -> o.name, "simop" -> (o.attributes.getAs[String]("simop") match {
            case Some(txid) => txid
            case _ =>
              o.attributes.getAs[String]("txid") match {
                case Some(txid) => txid
                case _ => "dummy"
              }
          }))
          case None => SPAttributes("name" -> "op does not exist")
        })
      case p: Parallel => {
        ack merge SPAttributes("parallel" -> p.sop.map(createExportJsonHelper(_, ids, ack)))
      }
      case s: Sequence => {
        ack merge SPAttributes("sequence" -> s.sop.map(createExportJsonHelper(_, ids, ack)))
      }
    }
  }

  def exportSeq(model: Option[ID], ids: List[IDAble], sops: List[ID], progress: ActorRef)(implicit rnr: RequestNReply) = {
    val sopspecs = ids.filter(_.isInstanceOf[SOPSpec]).map(_.asInstanceOf[SOPSpec]).filter(sop => sops.contains(sop.id))

    val json = SPAttributes("command" -> "create_op_chains",<commit_msg>Added extra conditions to PS export<commit_after>package sp.processSimulateImporter

import akka.actor._
import sp.domain.logic.{ActionParser, PropositionParser}
import sp.system._
import sp.system.messages._
import sp.domain._
import sp.domain.Logic._
import scala.concurrent.Future
import akka.util._
import akka.pattern.ask
import scala.concurrent._
import scala.concurrent.duration._
import akka.camel._

import scala.util._

/**
 * Some unclear interfaces. What is items?
 */

case class PSsetup(command: String, sops: List[ID])

object ProcessSimulateService extends SPService {
  val specification = SPAttributes(
    "service" -> SPAttributes(
      "group" -> "External",
      "description" -> "Pull/push data from/to Process Simulate"
    ),
    "setup" -> SPAttributes(
      "command" -> KeyDefinition("String", List("export seq", "import", "import_single", "update sim ids"), Some("export seq")),
      "sops" -> KeyDefinition("List[ID]", List(), Some(SPValue(List())))
    )
  )

  val transformTuple = (
    TransformValue("setup", _.getAs[PSsetup]("setup"))
    )
  val transformation = transformToList(transformTuple.productIterator.toList)

  def props(modelHandler: ActorRef, psAmq: ActorRef) = ServiceLauncher.props(Props(classOf[ProcessSimulateService], modelHandler, psAmq))
}

// activemq part    Beövs det inte en consumer också?
class ProcessSimulateAMQ extends Actor with Producer {
  implicit val timeout = Timeout(100 seconds)
  def endpointUri = "activemq:PS"
}

object ProcessSimulateAMQ {
  def props = Props(classOf[ProcessSimulateAMQ])
}

class ProcessSimulateService(modelHandler: ActorRef, psAmq: ActorRef) extends Actor with ServiceSupport {
  implicit val timeout = Timeout(100 seconds)

  import context.dispatcher

  def receive = {
    case r@Request(service, attr, ids, reqID) => {
      val replyTo = sender()
      implicit val rnr = RequestNReply(r, replyTo)
      val progress = context.actorOf(progressHandler)

      progress ! SPAttributes("progress" -> "creating a json for Process simulate")

      val setup = transform(ProcessSimulateService.transformTuple)
      val core = r.attributes.getAs[ServiceHandlerAttributes]("core").get

      val res = setup.command match {
        case "export seq" => exportSeq(core.model, ids, setup.sops, progress)
        case "import" => fetch(core.model, ids, progress)
        case "import_single" => fetch_single(core.model, ids, progress)
        case "update sim ids" => updateSimIds(ids, progress)
        case _ => throw new Exception("No such command! How to do this the scala way?")
      }

      res onComplete {
        case Success(resp) => {
          replyTo ! resp
          terminate(progress)
        }
        case Failure(t) => {
          replyTo ! SPError("Failed when communicating")
          terminate(progress)
        }
      }
    }
    case _ => sender ! SPError("Ill formed request");
  }

  def terminate(progress: ActorRef): Unit = {
    self ! PoisonPill
    progress ! PoisonPill
  }

  def createExportJsonHelper(sop : SOP, ids: List[IDAble], ack : SPAttributes) : SPAttributes = {
    import org.json4s.JString
    sop match {
      case h: Hierarchy =>
        val ops = ids.find(o => o.id == h.operation)
        ack merge (ops match {
          case Some(o) => SPAttributes("name" -> o.name, "simop" -> (o.attributes.getAs[String]("simop") match {
            case Some(txid) => txid
            case _ =>
              o.attributes.getAs[String]("txid") match {
                case Some(txid) => txid
                case _ => "dummy"
              }
          }), "needsToBeCompleted" -> o.asInstanceOf[Operation].conditions.flatMap({
            case PropositionCondition(EQ(SVIDEval(otherOpId), ValueHolder(JString("f"))),_,_) =>
              // for now, only handle when the operation is finished
              ids.find(o => o.id == otherOpId) match {
                case Some(otherOp) => otherOp.name
                case _ => None
              }
            case _ => None
          }))
          case None => SPAttributes("name" -> "op does not exist")
        })
      case p: Parallel => {
        ack merge SPAttributes("parallel" -> p.sop.map(createExportJsonHelper(_, ids, ack)))
      }
      case s: Sequence => {
        ack merge SPAttributes("sequence" -> s.sop.map(createExportJsonHelper(_, ids, ack)))
      }
    }
  }

  def exportSeq(model: Option[ID], ids: List[IDAble], sops: List[ID], progress: ActorRef)(implicit rnr: RequestNReply) = {
    val sopspecs = ids.filter(_.isInstanceOf[SOPSpec]).map(_.asInstanceOf[SOPSpec]).filter(sop => sops.contains(sop.id))

    val json = SPAttributes("command" -> "create_op_chains",
{'fraction_non_alphanumeric': 0.1225064803335963, 'fraction_numerical': 0.0014651189000338103, 'mean_word_length': 3.046511627906977, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 75, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5015560', 'n_tokens_mistral': 2691, 'n_tokens_neox': 2648, 'n_words': 663}