class ApiScoringController < ApiController

  respond_to :json
  before_filter :api_signed_in_user

  def work # clientid; returns another clientid
    clientid = params[:clientid]
    if clientid.blank? then render :json => {message: 'clientid not specified'}, :status => 400; return end

    conn = Connection.where(client_id: clientid, user_id: current_user.id).first
    if conn.nil? then render :json => {message: 'session not found'}, :status => 404; return end
    # if !current_user.id.eql?(conn.user.id) then render :json => {message: 'session not owned by user'}, :status => 403; return end

    #puts "ApiScoringController#work(#{clientid}) => locidispid #{c.locidispid}"
    result_client_id = JamRuby::GetWork.get_work(conn)
    #result_client_id = clientid+'peer'

    render :json => {:clientid => result_client_id}, :status => 200
  end

  def worklist # clientid; returns a list of clientid
    clientid = params[:clientid]
    if clientid.blank? then render :json => {message: 'clientid not specified'}, :status => 400; return end

    conn = Connection.where(client_id: clientid, user_id: current_user.id).first
    if conn.nil? then render :json => {message: 'session not found'}, :status => 404; return end

    if conn.locidispid.nil? then render :json => {message: 'no locidispid for connection'}, :status => 404; return end

    # if !current_user.id.eql?(conn.user.id) then render :json => {message: 'session not owned by user'}, :status => 403; return end

    result_client_ids = JamRuby::GetWork.get_work_list(conn, APP_CONFIG.getwork_result_size, APP_CONFIG.staleness_hours)
    #result_client_ids = [clientid+'peer1', clientid+'peer2']

    render :json => {:clientids => result_client_ids}, :status => 200
  end

  def record # aclientid, aAddr, bclientid, bAddr, score returns nothing

    aclientid = params[:aclientid]
    aip_address = params[:aAddr]
    bclientid = params[:bclientid]
    bip_address = params[:bAddr]
    score = params[:score]

    begin
      udpReachable = params[:detail][:sdetail][:udpReachable]
    rescue
      udpReachable = nil
    end

    score_data = params.to_s

    result = Score.record(current_user, aclientid, aip_address, bclientid, bip_address, score, score_data, udpReachable)

    if result[:error]
      render :json => {message: result[:message]}, :status => 422
    else
      render :json => {message: result[:message]}, :status => 200
    end
  end

end
