   require Logger
   alias FunWithFlags.{Config, Store}
 
-  # Host applications will inject this. It's supposed to be
-  # an active pubsub PID or name atom.
-  @conn Config.pubsub_client()
   @channel "fun_with_flags_changes"
+  @max_attempts 5
 
 
   def worker_spec do

  # The unique_id will become the state of the GenServer
  #
  def init(unique_id) do
    subscribe()
    {:ok, unique_id}
  end


  defp subscribe do
    try do
      case Phoenix.PubSub.subscribe(@conn, @channel) do
        :ok -> :ok
        {:error, reason} ->
          Logger.error "FunWithFlags: Cannot subscribe to Phoenix.PubSub process #{inspect(@conn)} ({:error, #{inspect(reason)}})."
      end
    rescue
      e ->
        Logger.error "FunWithFlags: Cannot subscribe to Phoenix.PubSub process #{inspect(@conn)} (exception: #{inspect(e)})."
    end
  end



    Task.start(Store, :reload, [name])
    {:noreply, unique_id}
  end


  # When subscribing to the pubsub process fails, the process sends itself a delayed message
  # to try again. It will be handlerd here.
  #
  def handle_info({:subscribe_retry, attempt}, unique_id) do
    Logger.debug "FunWithFlags: retrying to subscribe to Phoenix.PubSub, attempt #{attempt}."
    subscribe(attempt)
    {:noreply, unique_id}
  end

  defp client, do: Config.pubsub_client()
end

end # Code.ensure_loaded?
