 
   use GenStage
   alias Farmbot.BotState.Transport.HTTP.Router
+  alias Farmbot.System.ConfigStorage
 
   @port 27_347
 

  end

  def init([]) do
    s = Farmbot.System.ConfigStorage.get_config_value(:string, "authorization", "server")
    {:ok, {_, _, body}} = :httpc.request(:get, {'#{s}/api/public_key', []}, [], [body_format: :binary])
    public_key = body |> JOSE.JWK.from_pem
    # FIXME(Connor) The router should probably be put in an externally supervised module..
    case Plug.Adapters.Cowboy.http Router, [], [port: @port, acceptors: 2, dispatch: [cowboy_dispatch()]] do
      {:ok, web} ->
        state = %{web: web, bot_state: nil, sockets: [], public_key: public_key}
        Process.link(state.web)

    {:reply, {:ok, state.public_key}, [], state}
  end

  defp dispatch(Farmbot.BotState = dispatcher, events, state) do
    bot_state = List.last(events)
    for socket <- state.sockets do
      send socket, {dispatcher, bot_state}
    end
    {:noreply, [], %{state | bot_state: bot_state}}
  end

  defp dispatch(Farmbot.Logger = dispatcher, logs, state) do
    for socket <- state.sockets do
      send socket, {dispatcher, logs}
    end
    {:noreply, [], state}
