module JamRuby
  class GetWork < ActiveRecord::Base

    self.table_name = "connections"

    def self.get_work(connection, staleness_hours = 120)
      list = self.get_work_list(connection, 1, staleness_hours)
      return nil if list.nil?
      return nil if list.length == 0
      return list[0]
    end

    def self.get_work_list(connection, rows = 25, staleness_hours = 120)

      return [] if connection.is_network_testing # short-circuit 0 results if is_network_testing
      return [] unless connection.udp_reachable # short-circuit 0 results if udp_reachable
      return [] if connection.scoring_timeout > Time.now # short-circuit 0 results if in scoring timeout
      return [] if connection.in_session?

      r = GetWork.select(:client_id).find_by_sql("select get_work('#{connection.client_id}', #{connection.locidispid}, #{connection.addr}, #{rows}, INTERVAL '#{staleness_hours} hours') as client_id")
      #puts("r = #{r}")
      a = r.map {|i| i.client_id}
      #puts("a = #{a}")
      a
      #return ["blah1", "blah2", "blah3", "blah4", "blah5"]
    end

    def self.summary(staleness_hours = 120)
      r = GetWork.select([:work_count, :client_id, :email, :first_name, :last_name, :user_id, :udp_reachable, :in_timeout, :in_session, :scoring_failures, :scoring_failures_offset, :scoring_timeout_occurrences, :is_network_testing]).find_by_sql("select work_count, client_id, email, first_name, last_name, user_id, udp_reachable, in_timeout, in_session, scoring_failures, scoring_failures_offset, scoring_timeout_occurrences, is_network_testing FROM get_work_summary(INTERVAL '#{staleness_hours} hours')" )
    end
  end
end
