   alias Glasnost.Repo
   require Logger
   @blocks_per_tick 5
+  @lookback_max_blocks 201_600
 
   def start_link(args, options) do
     GenStage.start_link(__MODULE__, args, options)

  def init(%Glasnost.AgentConfig{} = config) do
    Logger.info("LookbackBlocks producer is initializing...")
    {:ok, %{head_block_number: head_block}} = config.client.get_dynamic_global_properties
    config = Map.put_new(config, :starting_block, head_block)
    config = Map.put_new(config, :current_block, head_block)
    Process.send_after(self(), :next_blocks, 5_000)
    {:producer, config, dispatcher: GenStage.BroadcastDispatcher, buffer_size: 100_000}
  end

    import Ecto.Query
    Logger.info("Starting to import blocks from #{state.current_block}")
    cur_block  = state.current_block
    start_block = state.starting_block
    event_mod = Module.concat([state.client, Event])
    tasks = for height <- cur_block..cur_block - @blocks_per_tick do
      Task.async(fn ->
       state.client.get_block(height)
     end)
    end
    blocks = Task.yield_many(tasks, 10_000)
    blocks = for {_, {:ok, {:ok, block}}} <- blocks do
      struct(event_mod, %{data: block, metadata: %{}})
    end
    if cur_block > start_block - @lookback_max_blocks do
      Process.send_after(self(), :next_blocks, 3_000)
      state = put_in(state.current_block, cur_block - @blocks_per_tick)
    else
      Logger.info("Lookbacks stage finished extracting past blocks...")
    end
    {:noreply, blocks, state}
  end

