package actors

import akka.actor.{Actor, ActorLogging, ActorRef}
import akka.event.LoggingReceive
import com.typesafe.scalalogging.LazyLogging

import scala.collection.immutable.{HashSet, Queue}
import scala.concurrent.duration._

case class DeciderMap(map: String, isBanned: Boolean = false)

/**
 * There is one StockActor per stock symbol.  The StockActor maintains a list of users watching the stock and the stock
 * values.  Each StockActor updates a rolling dataset of randomly generated stock values.
 */
class LobbieActor(lobbyName: String, hostUser: ActorRef) extends Actor with LazyLogging {

  private val name: String = lobbyName

  // user actors
  protected[this] var users: HashSet[ActorRef] = HashSet.empty[ActorRef]

  private var status = NotStarted

  private var maps: List[DeciderMap] = List(DeciderMap("map1"), DeciderMap("map2"), DeciderMap("map3"))

  private var secondPlayer: Option[ActorRef] = None

  logger.info(s"Create lobby with name $lobbyName")


  def receive = LoggingReceive {
    case BanMap(mapName: String) =>
      // notify watchers
      logger.info(s"Ban map $mapName by ${sender.path.name}")
      users.foreach(_ ! MapsUpdate( maps))
    case JoinLobbyAsPlayer(_) =>
      secondPlayer = Some(sender)
    case WatchLobby(_) =>
      // add the watcher to the list
      users = users + sender
    case LeaveLobby =>
      users = users - sender
      if(secondPlayer.contains(sender)) secondPlayer = None
      if (users.isEmpty) {
        logger.info(s"Stop lobby with name: $name")
        context.stop(self)
      }
    case InfoQuery =>
      sender ! LobbyInfoResponse(name, self.path.name, status.toString())
  }
}


case class BanMap(mapName: String)

case class MapsUpdate(maps: List[DeciderMap])

case class MapsHistory(symbol: String, maps: List[DeciderMap])

case class CreateLobby(userName: String)

case class JoinLobbyAsPlayer(lobbyName: String)

case class WatchLobby(lobbyName: String)

case class LeaveLobby(lobbyName: String)

case object InfoQuery

case class LobbyInfoResponse(lobbyName: String, lobbyActorName: String, status: String)

class LobbyStatus

sealed case class NotStarted() extends LobbyStatus
sealed case class Draft() extends LobbyStatus
sealed case class Finish() extends LobbyStatus
