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

module JamRuby

  # http://blog.bignerdranch.com/1643-never-use-resque-for-serial-jobs/
  # periodically scheduled to find sources that need to be brought down, or alternatively, it seems the client failed to start sourcing
  class IcecastSourceCheck
    extend Resque::Plugins::JamLonelyJob

    @queue = :scheduled_icecast_source_check

    def log
      @log || Logging.logger[IcecastSourceCheck]
    end

    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
      IcecastSourceCheck.new.run
    end


    def run
      # we need to find any mount in the following conditions and then poke it with a websocket msg.  here are the conditions:
      # * (if sourced_needs_changing_at has gone too far in the past OR sourced_needs_changing_at IS NULL) AND
      # ** listeners > 0 and sourced is DOWN (false)
      # ** listeners == 0 and sourced is UP (true)

      log.debug("waking up")

      IcecastMount.lock.where("( (listeners > 0 AND sourced = FALSE) OR (listeners = 0 AND sourced = TRUE) ) AND ( sourced_needs_changing_at IS NULL OR sourced_needs_changing_at < (NOW() - interval '#{APP_CONFIG.icecast_max_sourced_changed} second') ) ").find_each(:batch_size => 100) do |mount|
        if mount.music_session_id
          mount.with_lock do
            handle_notifications(mount)
          end
        end
      end

      log.debug("done")
    end

    def handle_notifications(mount)
      if mount.listeners == 0 && mount.sourced
        # if no listeners, but we are sourced, then ask it to stop sourcing
        log.debug("SOURCE_DOWN_REQUEST called on mount #{mount.name}")

        mount.notify_source_down_requested

      elsif mount.listeners > 0 && !mount.sourced
        # if we have some listeners, and still are not sourced, then ask to start sourcing again
        log.debug("SOURCE_UP_REQUEST called on mount #{mount.name}")

        mount.notify_source_up_requested
      end
    end
  end
end