 require Logger
 
 defmodule Serverboards.Plugin.Registry do
+  use GenServer
+
   def start_link(options \\ []) do
-    {:ok, pid} = Agent.start_link(&load_plugins/0, options)
-
-    Serverboards.Plugin.Monitor.start_link
-    plugins = Agent.get pid, &(&1)
-    Logger.info("Starting plugin registry #{inspect pid}, got #{Enum.count plugins}")
+    {:ok, pid} = GenServer.start_link(__MODULE__, [], [name: Serverboards.Plugin.Registry] ++ options)
 
     {:ok, pid}
   end

          nil ->
            nil
          [plugin_id] ->
            plugins = Agent.get registry, &(&1)
            Enum.find(plugins, &(&1.id == plugin_id) )
        end
      [_, plugin_id, component_id] ->
        plugins = Agent.get registry, &(&1)

        with %Plugin{} = plugin <- Enum.find(plugins, &(&1.id == plugin_id) ),
             %Plugin.Component{} = component <- Enum.find(plugin.components, &(&1.id == component_id) )
        do
           %Plugin.Component{ component | plugin: plugin, id: "#{plugin.id}/#{component.id}" }

    list(Serverboards.Plugin.Registry)
  end


  ## server impl, jsut stores state
  def init([]) do
    Serverboards.Plugin.Monitor.start_link

    GenServer.cast(self, {:reload})
    {:ok, %{ active: [], all: []}}
  end

  def decorate_plugin(p) do
    Logger.debug("#{inspect p}")
    p
  end

  def handle_cast({:reload}, _status) do
    all_plugins = load_plugins
      |> Enum.map(&decorate_plugin/1)

    {:noreply, %{
      all: all_plugins,
      active: all_plugins
      }}
  end

  def handle_call({:get_all}, _from, state) do
    {:reply, state.all, state}
  end
  def handle_call({:get_active}, _from, state) do
    {:reply, state.active, state}
  end

end
