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

module JamRuby

  class ActiveMusicSessionCleaner
    extend Resque::Plugins::JamLonelyJob

    attr_accessor :interval

    @queue = :active_music_session_cleaner

    @@log = Logging.logger[ActiveMusicSessionCleaner]

    def self.lock_timeout
      120
    end

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

      cleaner = ActiveMusicSessionCleaner.new
      cleaner.interval = "INTERVAL '1 minute'"
      cleaner.run

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

    def run
      # get all active sessions where there are no connections
      stale_sessions = ActiveMusicSession.includes(:connections)
        .where("active_music_sessions.updated_at < NOW() - #{self.interval}")

      stale_sessions.each do |s|
        if s.connections.count == 0
          s.before_destroy
          s.delete
        end
      end
    end
  end
end