48 lines
1.3 KiB
Elixir
48 lines
1.3 KiB
Elixir
defmodule Localiser.Localisation.Room.Manager do
|
|
@moduledoc """
|
|
Per-floor GenServer that reacts to room lifecycle events and drives Room.Supervisor.
|
|
|
|
- {:room_created, room} → start a Room.Server (if room belongs to this floor)
|
|
- {:room_deleted, room_id, floor_id} → terminate the Room.Server (if on this floor)
|
|
"""
|
|
|
|
use GenServer
|
|
|
|
alias Localiser.Localisation.Room
|
|
|
|
def start_link(floor) do
|
|
GenServer.start_link(__MODULE__, floor.id, name: via(floor.id))
|
|
end
|
|
|
|
def via(floor_id) do
|
|
{:via, Registry, {Localiser.Registry, {:room_manager, floor_id}}}
|
|
end
|
|
|
|
@impl true
|
|
def init(floor_id) do
|
|
Phoenix.PubSub.subscribe(Localiser.PubSub, "rooms")
|
|
{:ok, %{floor_id: floor_id}}
|
|
end
|
|
|
|
@impl true
|
|
def handle_info({:room_created, %{floor_id: floor_id} = room}, %{floor_id: floor_id} = state) do
|
|
case Registry.lookup(Localiser.Registry, {:room, room.id}) do
|
|
[] -> Room.Supervisor.start_room_server(floor_id, room)
|
|
_ -> :ok
|
|
end
|
|
|
|
{:noreply, state}
|
|
end
|
|
|
|
def handle_info({:room_deleted, room_id, floor_id}, %{floor_id: floor_id} = state) do
|
|
case Registry.lookup(Localiser.Registry, {:room, room_id}) do
|
|
[{pid, _}] -> DynamicSupervisor.terminate_child(Room.Supervisor.via(floor_id), pid)
|
|
[] -> :ok
|
|
end
|
|
|
|
{:noreply, state}
|
|
end
|
|
|
|
def handle_info(_msg, state), do: {:noreply, state}
|
|
end
|