workers Integer(ENV['WEB_CONCURRENCY'] || 1)
threads_count = Integer(ENV['MAX_THREADS'] || 24)

#threads threads_count, threads_count
threads 8, threads_count

preload_app!

#rackup      DefaultRackup
port        ENV['PORT']     || 3000
environment ENV['RACK_ENV'] || 'development'

# is web_workers 1
silence_single_worker_warning

#on_worker_boot do
#  # Worker specific setup for Rails 4.1+
#  # See: https://devcenter.heroku.com/articles/deploying-rails-applications-with-the-puma-web-server#on-worker-boot
#  ActiveRecord::Base.establish_connection
#end

#on_worker_boot do
#  # Valid on Rails up to 4.1 the initializer method of setting `pool` size
#  ActiveSupport.on_load(:active_record) do
#    config = ActiveRecord::Base.configurations[Rails.env] ||
#                Rails.application.config.database_configuration[Rails.env]
#    config['pool'] = ENV['RAILS_MAX_THREADS'] || 5
#    ActiveRecord::Base.establish_connection(config)
#  end
#end

on_worker_boot do
  Thread.new do
    $redis_worker = Redis.new(url: ENV['REDIS_URL'])
    api = Papamira_API.new

    begin
      loop do
        sleep 0.2
        next if $redis_worker.llen("worker_spool") == 0

        method_raw = $redis_worker.lrange("worker_spool", 0, 1).first
        next if method_raw.nil?

        method_json = JSON.parse(method_raw)
        pp "worker run: " + method_json['namespace']

        case method_json['namespace']
        when 'search_word_save'
          s = method_json['server']
          w = method_json['word']

          ActiveRecord::Base.connection_pool.release_connection
          ActiveRecord::Base.connection_pool.with_connection do
            api.search_word_save(s, w)
          end
          pp "worker run: " + method_json['namespace'] + " done."

          api.search_word_push(s, w)
          pp "worker run: search_word_push done."
        else
          pp "no match namespace. : " + method_json['namespace']
        end

        $redis_worker.lpop("worker_spool")
        pp "worker spool remove"

        ObjectSpace.each_object(ActiveRecord::Relation).each(&:reset)
        GC.start
      end
    rescue => e
      pp "worker abort"
      pp "worker Log: " + e.to_s
      sleep 5.0
      retry
    end
  end
end
