module Sidekiq
  module HerokuAutoscale

    class PollInterval
      def initialize(method_name, before_update: 0, after_update: 0)
        @method_name = method_name
        @before_update = before_update
        @after_update = after_update
        @requests = {
          'small_worker' => nil,
          'medium_worker' => nil,
          'large_worker' => nil,
          'premium_worker' => nil,
        }
      end

      def call(process)
        if !process&.name
          return
        end
        @requests[process.name] = process
        poll!
      end

      def poll!
        requests = @requests.compact

        @thread = nil if (!@thread&.status)
        @thread ||= Thread.new do
          begin
            while requests.size > 0
              if @before_update > 0
                sleep(@before_update)
              end
              requests.reject! { |n, p| p.send(@method_name) }
              if @after_update > 0
                sleep(@after_update)
              end
            end
          ensure
            @thread = nil
          end
        end
      end
    end

  end
end