class ApiClaimedRecordingsController < ApiController

  before_filter :api_signed_in_user, :except => [ :download, :show ]
  before_filter :look_up_claimed_recording, :only => [ :show, :update, :delete, :download ]

  respond_to :json

  def index
    @claimed_recordings = ClaimedRecording.where(:user_id => current_user.id).order("created_at DESC").paginate(page: params[:page], per_page: params[:per_page])
    response.headers['total-entries'] = @claimed_recordings.total_entries.to_s
  end

  def show
    if !@claimed_recording.is_public && @claimed_recording.user_id != current_user.id
      raise JamPermissionError, 'this claimed recording is not public'
    end
  end
  
  def update
    if @claimed_recording.user_id != current_user.id
      raise JamPermissionError, 'only owner of claimed_recording can update it'
    end

    @claimed_recording.update_fields(current_user, params)
    respond_with @claimed_recording
  end
  
  def delete
    if @claimed_recording.user_id != current_user.id
      raise JamPermissionError, 'only owner of claimed_recording can update it'
    end
    @claimed_recording.discard(current_user)
    respond_with @claimed_recording
  end

  def download
    unless @claimed_recording.is_public
      if current_user.nil? || @claimed_recording.user_id != current_user.id
        raise JamPermissionError, 'this claimed recording is not public'
      end
    end

    params[:type] ||= 'ogg'

    mix = @claimed_recording.recording.mix

    if mix && mix.completed
      redirect_to mix.sign_url(120, params[:type])
    else
      quick_mix = @claimed_recording.recording.stream_mix

      if quick_mix
        redirect_to quick_mix.sign_url(120, params[:type])
      else
        render :json => {}, :status => 404
      end
    end
  end

  private

  def look_up_claimed_recording
    @claimed_recording = ClaimedRecording.find(params[:id])
    if @claimed_recording.nil?
      render :json => { :message => "claimed_recording not found" }, :status => 404 
    end
  end

end
