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

import akka.actor.Actor
import akka.actor.ActorSystem
import akka.actor.TypedActor
import akka.actor.TypedProps

trait Test2 {
  def done(): Unit
  def message(msg: String, sender: Test1): Unit
}

class Test2Impl extends Test2 {
  def done(): Unit = {
    TypedActor.get(TypedActor.context).stop(this)
  }
  def message(msg: String, sender: Test1): Unit = {
    println(s"Test2: ${msg} (thread: ${Thread.currentThread().getId()})")
    sender.ack()
  }
}

trait Test1 {
  def ack(): Unit
  def done(): Unit
  def message(msg: String): Unit
}

class Test1Impl() extends Test1 {
  val test2: Test2 = TypedActor(TypedActor.context).typedActorOf(TypedProps[Test2Impl]())
  def ack(): Unit = {
    println(s"Test1: ACK from Test2 (thread: ${Thread.currentThread().getId()})")
  }
  def done(): Unit = {
    test2.done()
    TypedActor.get(TypedActor.context).stop(this)
  }
  def message(msg: String): Unit = {
    println(s"Test1: ${msg} (thread: ${Thread.currentThread().getId()})")
    test2.message(msg, TypedActor.self)
  }
}

object Test {
  def main(args: Array[String]): Unit = {
    println(s"main (thread: ${Thread.currentThread().getId()})")
    val akka = ActorSystem.create("Demo")
    val test1: Test1 = TypedActor(akka).typedActorOf(TypedProps[Test1Impl]())
    test1.message("Hello world!")
    test1.message("Hello world!")
    test1.message("Hello world!")
    Thread.sleep(100)
    test1.done()
    akka.terminate()
  }
}
