class ApiJamTracksController < ApiController

  # have to be signed in currently to see this screen
  before_filter :api_signed_in_user, :except => [:index, :show, :show_with_artist_info, :artist_index]
  before_filter :api_any_user, :only => [:index, :show, :show_with_artist_info, :artist_index]
  before_filter :lookup_jam_track_right, :only => [:download,:enqueue, :show_jam_track_right]
  
  respond_to :json

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

  def show
    @jam_track = JamTrack.find_by_plan_code!(params[:plan_code])
  end

  def show_with_artist_info
    @jam_track = JamTrack.find_by_plan_code!(params[:plan_code])
  end

  def index    
    data = JamTrack.index(params, any_user)
    @jam_tracks, @next = data[0], data[1]
    
    render "api_jam_tracks/index", :layout => nil
  end

  def artist_index
    data = JamTrack.artist_index(params, any_user)
    @artists, @next = data[0], data[1]

    render "api_jam_tracks/artist_index", :layout => nil
  end

  def played
    if params[:id].blank?
      render(:json => { :message => "JamTrack ID required" }, :status => 400) and return 
    end
    play = PlayablePlay.new
    play.player_id = current_user.id
    play.ip_address = request.remote_ip

    unless current_user.first_played_jamtrack_at
      User.where(id: current_user.id).update_all(first_played_jamtrack_at: Time.now)
      current_user.first_played_jamtrack_at = Time.now
    end

    # VRFS-2916 jam_tracks.id is varchar: REMOVE
    # play.jam_track = JamTrack.where(id: params[:id].to_i).first
    # VRFS-2916 jam_tracks.id is varchar: ADD
    play.playable = JamTrack.where(id: params[:id]).first

    play.save

    if play.errors.any?
      render :json => { :message => "Unexpected error occurred" }, :status => 500
    else
      render :json => {}, :status => 201
    end
  end

  def purchased
    params[:show_purchased_only] = true
    data = JamTrack.index(params, current_user)
    @jam_tracks, @next = data[0], data[1]

    response.headers['total-entries'] = @jam_tracks.total_entries.to_s

    render "api_jam_tracks/purchased", :layout => nil
  end


  def download
    if @jam_track_right.valid?

      all_fingerprint = params[:all_fp]
      running_fingerprint = params[:running_fp]

      if Rails.application.config.guard_against_fraud
        error = @jam_track_right.guard_against_fraud(current_user, {all:all_fingerprint, running: running_fingerprint}, request.remote_ip)
        if error
          log.warn("potential fraud detected: #{error}")
          render :json => { :message => error }, :status => 403
          return
        end
      end

      sample_rate = params[:sample_rate].nil? ? nil : params[:sample_rate].to_i
      if @jam_track_right && @jam_track_right.ready?(sample_rate)
        @jam_track_right.update_download_count
        now = Time.now
        @jam_track_right.last_downloaded_at = now
        @jam_track_right.first_downloaded_at = now if @jam_track_right.first_downloaded_at.nil?
        @jam_track_right.save!
        redirect_to @jam_track_right.sign_url(120, sample_rate)
      else
        @jam_track_right.enqueue_if_needed(sample_rate)
        render :json => { :message => "not available, digitally signing Jam Track offline." }, :status => 202
      end
    else
      render :json => { :message => "download limit surpassed", :errors=>@jam_track_right.errors }, :status => 403
    end        
  end

  def enqueue

    fingerprint = params[:fingerprint]

    if Rails.application.config.guard_against_fraud
      error = @jam_track_right.guard_against_fraud(current_user, fingerprint, request.remote_ip)
      if error
        log.warn("potential fraud detected: #{error}")
        render :json => { :message => error }, :status => 403
        return
      end
    end

    sample_rate = params[:sample_rate].nil? ? nil : params[:sample_rate].to_i
    enqueued = @jam_track_right.enqueue_if_needed(sample_rate)
    log.debug("jamtrack #{enqueued ? "ENQUEUED" : "NOT ENQUEUED"}: jam_track_right=#{@jam_track_right.id} sample_rate=#{sample_rate} ")
    render :json => { :message => "enqueued" }, :status => 200
  end

  def show_jam_track_right

  end

  def keys
    jamtrack_holder = params[:jamtracks]

    unless jamtrack_holder.kind_of?(Hash)
      render :json => {message: 'jamtracks parameter must be an hash'}, :status => 422
      return
    end

    jamtracks = jamtrack_holder[:tracks]

    unless jamtracks.kind_of?(Array)
      render :json => {message: 'jamtracks:tracks parameter must be an array'}, :status => 422
      return
    end


    # jamtracks come in the form id-44 or id-48, so we need to do a little extra parsing

    jamtrack_ids = Set.new
    jamtracks_fq_ids = Set.new
    jamtracks.each do |jamtrack|
      rindex = jamtrack.rindex('-')
      if rindex
        id = jamtrack[0..(rindex-1)]
        jamtrack_ids << id
        jamtracks_fq_ids << jamtrack # includes sample rate
      end
    end

    @jam_tracks = JamTrackRight.list_keys(current_user, jamtrack_ids)
    @jamtracks_fq_ids = jamtracks_fq_ids
  end

private
  def lookup_jam_track_right
    @jam_track_right = JamTrackRight.where("jam_track_id=? AND user_id=?", params[:id], current_user.id).first
    raise JamPermissionError, ValidationMessages::PERMISSION_VALIDATION_ERROR unless @jam_track_right
  end

end # class ApiJamTracksController
