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

import scala.util.Failure
import scala.util.Success
import scala.concurrent.duration._

import org.apache.pekko.actor.typed.ActorRef
import org.apache.pekko.actor.typed.ActorSystem
import org.apache.pekko.actor.typed.Behavior
import org.apache.pekko.actor.typed.scaladsl.AskPattern._
import org.apache.pekko.actor.typed.scaladsl.Behaviors
import org.apache.pekko.util.Timeout

object Test2 {
  val DONE = "__DONE__"
  case class Message(val text: String, val sender: ActorRef[Test1.Message])
  def apply(): Behavior[Message] = Behaviors.receive { (ctx, msg) =>
    msg.text match {
      case DONE => Behaviors.stopped
      case _ => {
        println(s"Test2: ${msg.text} (thread: ${Thread.currentThread().getId()})")
        msg.sender ! Test1.Message(Test1.ACK)
        Behaviors.same
      }
    }
  }
}

object Test1 {
  val ACK = "__ACK__"
  val DONE = "__DONE__"
  case class Message(val text: String)
  def apply(): Behavior[Message] = Behaviors.setup { ctx =>
      val test2 = ctx.spawn(Test2(), "Test2")
      Behaviors.receive { (ctx, msg) =>
        msg.text match {
          case ACK => {
            println(s"Test1: ACK from Test2 (thread: ${Thread.currentThread().getId()})")
            Behaviors.same
          }
          case DONE => {
            test2 ! Test2.Message(Test2.DONE, ctx.self)
            Behaviors.stopped
          }
          case _ => {
            println(s"Test1: ${msg.text} (thread: ${Thread.currentThread().getId()})")
            implicit val duration: Timeout = Duration(100, MILLISECONDS)
            implicit val scheduler = ctx.system.scheduler
            implicit val ec = ctx.system.executionContext
            val fut = test2 ? ((me: ActorRef[Message]) => new Test2.Message(msg.text, me))
            fut.onComplete {
              case Success(msg) => println(s"Reply received: ${msg.text.replace("_", "")} (thread: ${Thread.currentThread().getId()})")
              case Failure(ex) => println("ooops")
            }
            Behaviors.same
        }
      }
    }
  }
}

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