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

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

    @queue = :unused_music_notation_cleaner

    @@log = Logging.logger[UnusedMusicNotationCleaner]

    def self.lock_timeout
      # this should be enough time to make sure the job has finished, but not so long that the system isn't recovering from a abandoned job
      120
    end

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

      UnusedMusicNotationCleaner.new.run

      @@log.debug("done")
    end


    def run
      MusicNotation.find_each do |music_notation|
        if music_notation.music_session && music_notation.music_session.session_removed_at
          handle_notifications music_notation if music_notation.music_session.session_removed_at + 1.day < Time.now
        elsif music_notation.music_session.nil?
          handle_notifications music_notation if music_notation.created_at + 1.day < Time.now
        end
      end
    end

    def handle_notifications music_notation
      music_notation.destroy
    end
  end
end