defmodule ZoeyscomputerWeb.HomeLive do
  use ZoeyscomputerWeb, :live_view

  def mount(_params, _session, socket) do
    if connected?(socket) do
      :timer.send_interval(750, self(), :update_stats)
    end

    socket = assign(socket, cpu_usage: 0, memory_usage: 0, page_title: "home")

    {:ok, socket}
  end

  def handle_info(:update_stats, socket) do
    {:noreply, assign(socket, get_stats())}
  end

  defp get_stats do
    cpu_usage = :cpu_sup.util()
    mem_data = :memsup.get_system_memory_data()

    total_memory = Keyword.get(mem_data, :system_total_memory, 0)
    free_memory = Keyword.get(mem_data, :free_memory, 0)
    buff_memory = Keyword.get(mem_data, :buffered_memory, 0)
    cached_memory = Keyword.get(mem_data, :cached_memory, 0)

    memory_usage =
      if total_memory > 0 do
        100 - (free_memory + buff_memory + cached_memory) * 100 / total_memory
      else
        0
      end

    %{
      cpu_usage: Float.round(cpu_usage, 2),
      memory_usage: Float.round(memory_usage, 2)
    }
  end

  def render(assigns) do
    ~H"""
    <div class="container p-8 flex justify-center align-middle">
      <div class="border border-ctp-overlay0 rounded-md p-8 flex-col flex items-center">
        <h1 class="font-bold text-ctp-mauve">zoey</h1>
        <p class="text-ctp-text"><i>Software Engineer 🏳️‍⚧️</i></p>
        <p class="max-w-96 text-center mt-4 text-ctp-overlay2">
          Currently cooking this up, stay tuned... in the meantime, you can monitor my server's resources.
        </p>
        <div class="grid w-full text-center font-bold mt-4 grid-cols-2 gap-2">
          <p class="text-ctp-overlay2 bg-ctp-crust p-2 rounded-md w-full border-ctp-mauve border">
            CPU: <%= @cpu_usage %>%
          </p>
          <p class="text-ctp-overlay2 bg-ctp-crust p-2 rounded-md w-full border-ctp-sapphire border">
            MEM: <%= @memory_usage %>%
          </p>
        </div>
        <div class="text-ctp-overlay2 mt-4">
          <%= if @current_user && @current_user.email == "hi@zoeys.computer" do %>
            <p>
              You are already signed in you silly billy
            </p>
          <% else %>
            <p>
              Are you me?
              <.link class="font-bold text-ctp-pink" navigate={~p"/users/log_in"}>Log in.</.link>
            </p>
          <% end %>
        </div>
      </div>
    </div>
    """
  end
end
