package wow.doge.mygame.utils

import akka.actor.typed.ActorRef
import akka.actor.typed.Behavior
import akka.actor.typed.Props
import akka.actor.typed.Scheduler
import akka.actor.typed.SpawnProtocol
import akka.util.Timeout
import wow.doge.mygame.AppError.TimeoutError
import wow.doge.mygame.implicits._

object AkkaUtils {

  def spawnActorOldL[T](
      spawnProtocol: ActorRef[SpawnProtocol.Command],
      actorName: String,
      behavior: Behavior[T]
  )(implicit timeout: Timeout, scheduler: Scheduler) =
    spawnProtocol.askL[ActorRef[T]](
      SpawnProtocol.Spawn(
        behavior,
        actorName,
        Props.empty,
        _
      )
    )
  def spawnActorL[T](
      behavior: Behavior[T],
      actorName: Option[String] = None,
      props: Props = Props.empty
  )(implicit
      timeout: Timeout,
      scheduler: Scheduler,
      spawnProtocol: ActorRef[SpawnProtocol.Command],
      name: sourcecode.Name
  ) =
    spawnProtocol
      .askL[ActorRef[T]](
        SpawnProtocol.Spawn(
          behavior,
          actorName.fold(name.value)(identity),
          props,
          _
        )
      )
      .onErrorHandleWith(TimeoutError.from)
}
