require 'json'
require 'resque'
require 'resque-retry'
require 'net/http'
require 'digest/md5'

module JamRuby
  class MusicSessionScheduler
    extend Resque::Plugins::JamLonelyJob

    @queue = :music_session_scheduler

    @@log = Logging.logger[MusicSessionScheduler]

    def self.lock_timeout
      120
    end

    def self.perform
      @@log.debug("MusicSessionScheduler waking up")

      MusicSessionScheduler.new.run

      @@log.debug("MusicSessionScheduler done")
    end

    def run
      # get all weekly sessions that started at least 4 hours ago
      criteria = "recurring_mode = 'weekly' AND scheduled_start + interval '4hours' < NOW() AND canceled = false AND next_session_scheduled = false"
      MusicSession.where(criteria).find_each do |music_session|
        music_session.copy
      end
    end
  end
end