require 'resque/tasks'
require 'resque/scheduler/tasks'

namespace :resque do
  task setup: :environment do
    resque = Module.new do
      def identify(*)
        super
        flush
      end

      def track(*)
        super
        flush
      end
    end

    ThreeScale::Analytics::UserTracking.prepend(resque)

    # set a custom formatter to show PID
    Rails.logger.formatter = Class.new(Logger::Formatter) do
      def msg2str(msg)
        msg = super
        "[#{Process.pid}] #{msg}"
      end
    end.new
  end

  task setup_schedule: :setup do
    require 'resque-scheduler'
    Resque::Scheduler.dynamic = true
  end

  task scheduler_setup: :setup_schedule

  task web: :environment do
    require 'resque/server'
    app = Resque::Server
    app.set :environment, Rails.env
    app.set :bind, '0.0.0.0'
    app.set :port, ENV.fetch('PORT', 9495)
    app.run!
  end


end

begin
  require 'resque/pool/tasks'
  namespace :resque do

    namespace :pool do
      task :setup do
        # close any sockets or files in pool manager
        ActiveRecord::Base.connection.disconnect!
        # and re-open them in the resque worker parent
        Resque::Pool.after_prefork do |job|
          ActiveRecord::Base.establish_connection
          Resque.redis.client.reconnect
        end
      end
    end
  end
rescue LoadError
  # resque-pool not available
end
