defmodule ReactDemoWeb.SystemUsageChannel do
  use ReactDemoWeb, :channel

  @impl true
  def join("system_usage:lobby", payload, socket) do
    if authorized?(payload) do
      send(self(), :after_join)
      {:ok, socket}
    else
      {:error, %{reason: "unauthorized"}}
    end
  end

  @impl true
  def handle_info(:after_join, socket) do
    stats = SystemStats.get_stats()

    data =
      stats
      |> Enum.map(fn {time, cpu, mem} ->
        %{date: time, cpu: cpu, mem: mem}
      end)

    push(socket, "joined", %{
      message: "Welcome to the system usage lobby!",
      time: DateTime.utc_now(),
      data: data
    })

    {:noreply, socket}
  end

  # Channels can be used in a request/response fashion
  # by sending replies to requests from the client
  @impl true
  def handle_in("ping", payload, socket) do
    {:reply, {:ok, payload}, socket}
  end

  # It is also common to receive messages from the client and
  # broadcast to everyone in the current topic (system_usage:lobby).
  @impl true
  def handle_in("shout", payload, socket) do
    broadcast(socket, "shout", payload)
    {:noreply, socket}
  end

  # Add authorization logic here as required.
  defp authorized?(_payload) do
    true
  end
end
