package actors

import akka.actor.{Actor, ActorLogging, Props}
import akka.event.LoggingReceive
import akka.pattern.ask
import akka.util.Timeout
import com.typesafe.scalalogging.LazyLogging

import scala.collection.mutable.ListBuffer
import scala.concurrent.Await
import scala.concurrent.duration.DurationInt

class LobbiesActor extends Actor with LazyLogging {

  implicit val timeout: Timeout = 1.second

  val lobbies: ListBuffer[String] = ListBuffer()

  def receive = LoggingReceive {
    case CreateLobby(userName) =>
      val lobbyActor = context.actorOf(Props(new LobbieActor(userName, sender)),
        s"lobbyActor-${(math.random*100000000L).toLong}")
      lobbyActor.tell(WatchLobby("watchIt"), sender)
    case watchLobby@WatchLobby(lobbyName) =>
      // get or create the StockActor for the symbol and forward this message
      context.child(lobbyName) match {
        case Some(lobbyActor) => lobbyActor forward watchLobby
        case None => logger.error(s"Can't watch lobby $lobbyName - lobby not exists")
      }
    case unwatchLobby@LeaveLobby(symbol) =>
      // if there is a StockActor for the symbol forward this message
      context.child(symbol).foreach(_.forward(unwatchLobby))
    case banMap@BanMap(map) =>
      logger.info(s"forvard ban $map")
      context.children.foreach(_.forward(banMap))
    case UnWatchAllLobbies =>
      context.children.foreach( _.tell(LeaveLobby, sender))
    case GetAllLobbies =>
      sender ! context.children.toList.map(lobbyActor =>
        Await.result(lobbyActor ? InfoQuery, 1.second))

  }

}

case object GetAllLobbies

case object UnWatchAllLobbies