class ApiMixesController < ApiController

  # This must be present on requests from the cron to prevent hackers from
  # hitting these routes.
  CRON_TOKEN = "2kkl39sjjf3ijdsflje2923j"

  before_filter :api_signed_in_user, :only => [ :schedule ]
  before_filter :require_cron_token, :only => [ :next, :finish ]
  before_filter :look_up_mix, :only => [ :finish ]

  respond_to :json

  def schedule
    begin
      Mix.schedule(params[:recording_id], current_user, params[:description], params[:manifest])
      respond_with responder: ApiResponder, :status => 204
    rescue
     render :json => { :message => "mix could not be scheduled" }, :status => 403
    end
  end
  
  def next
    begin
      mix = Mix.next(params[:server])
      respond_with responder: ApiResponder, :status => 204 if mix.nil?
      render :json => { :id => mix.id, :manifest => mix.manifest, :destination => mix.s3_url }, :status => 200
    rescue
     render :json => { :message => "next mix could not be found" }, :status => 403
    end
  end
 
  def finish
    begin
      @mix.finish
    rescue
      render :json => { :message => "mix finish failed" }, :status => 403
    end
    respond_with responder: ApiResponder, :status => 204
  end
  
  private

  def look_up_mix
    @mix = Mix.find(params[:id])
    if @mix.nil? || (!@is_cron && @mix.owner_id != current_user.id)
      render :json => { :message => "mix not found" }, :status => 404 
    end
  end
  
  def require_cron_token
    render :json => { :message => "bad token" }, :status => 403 unless params[:token] == CRON_TOKEN
    @is_cron = true
  end

end
