class ApiRecordingsController < ApiController

  before_filter :api_signed_in_user
  before_filter :look_up_recording, :only => [ :stop, :claim ]
  before_filter :parse_filename, :only => [ :upload_next_part, :upload_sign, :upload_part_complete, :upload_complete ]

  respond_to :json

  # Returns all files this user should have synced down to his computer
  def list
    begin
      render :json => Recording.list(current_user), :status => 200
    rescue
      render :json => { :message => "could not produce list of files" }, :status => 403
    end
  end

  def start
    begin
      Recording.start(params[:music_session_id], current_user)
      respond_with responder: ApiResponder, :status => 204
    rescue
      render :json => { :message => "recording could not be started" }, :status => 403
    end
  end
  
  def stop
    begin
      if @recording.owner_id != current_user.id
        render :json => { :message => "recording not found" }, :status => 404 
      end
      @recording.stop
      respond_with responder: ApiResponder, :status => 204      
    rescue
      render :json => { :message => "recording could not be stopped" }, :status => 403
    end
  end
  

  def claim
    begin
      claimed_recording = @recording.claim(current_user, params[:name], Genre.find(params[:genre_id]), params[:is_public], params[:is_downloadable])
      render :json => { :claimed_recording_id => claimed_recording.id }, :status => 200
    rescue
      render :json => { :message => "recording could not be claimed" }, :status => 403
    end
  end
  
  def upload_next_part
    if @recorded_track.next_part_to_upload == 0
      if (!params[:length] || !params[:md5])
        render :json => { :message => "missing fields" }, :status => 403
      end
      @recorded_track.upload_start(params[:length], params[:md5])
    end
    
    render :json => { :part => @recorded_track.next_part_to_upload }, :status => 200
  end

  def upload_sign
    render :json => @recorded_track.upload_sign(params[:content_md5]), :status => 200
  end

  def upload_part_complete
    begin
      @recorded_track.upload_part_complete(params[:part])
    rescue
      render :json => { :message => "part out of order" }, :status => 403
    end
    respond_with responder: ApiResponder, :status => 204
  end
  
  def upload_complete
    @recorded_track.upload_complete
    respond_with responder: ApiResponder, :status => 204
  end

  private

  def parse_filename
    @recorded_track = RecordedTrack.find_by_upload_filename(params[:filename])
    unless @recorded_track 
      render :json => { :message => RECORDING_NOT_FOUND }, :status => 404 
    end    
  end

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

end
