// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
//package actor.pekko.classic.untyped

import org.apache.pekko.actor.Actor
import org.apache.pekko.actor.ActorSystem
import org.apache.pekko.actor.PoisonPill
import org.apache.pekko.actor.Props

object Test2Command extends Enumeration {
  type Command  = Value
  val DONE = Value
}
case class Test2Message(val text: String)

class Test2 extends Actor {
  def receive = {
    case Test2Command.DONE => self ! PoisonPill
    case msg: Test2Message => {
      println(s"Test2: ${msg.text} (thread: ${Thread.currentThread().getId()})")
      sender() ! Test1Command.ACK
    }
    case _ => println("Unknown message")
  }
}

object Test1Command extends Enumeration {
  type Command  = Value
  val ACK, DONE = Value
}
case class Test1Message(val text: String)

class Test1 extends Actor {
  val test2 = context.actorOf(Props[Test2]())
  def receive = {
    case Test1Command.ACK => println(s"Test1: ACK from Test2 (thread: ${Thread.currentThread().getId()})")
    case Test1Command.DONE => {
      test2 ! Test2Command.DONE
      self ! PoisonPill
    }
    case msg: Test1Message => {
      println(s"Test1: ${msg.text} (thread: ${Thread.currentThread().getId()})")
      test2 ! new Test2Message(msg.text)
    }
    case _ => println("Unknown message")
  }
}

object Test {
  def main(args: Array[String]): Unit = {
    println(s"main (thread: ${Thread.currentThread().getId()})")
    val akka = ActorSystem.create("Demo")
    val test1 = akka.actorOf(Props[Test1]())
    test1 ! new Test1Message("Hello world!")
    test1 ! new Test1Message("Hello world!")
    test1 ! new Test1Message("Hello world!")
    Thread.sleep(100)
    test1 ! Test1Command.DONE
    akka.terminate()
  }
}
