require 'sanitize'
class ApiReviewsController < ApiController
  before_filter :api_signed_in_user, :except => [:index]
  before_filter :lookup_review_summary, :only => [:details]
  before_filter :lookup_review, :only => [:update, :delete, :show]

  respond_to :json

  # List review summaries according to params:
  def index
    summaries = ReviewSummary.index(params[:review])
    @reviews = summaries.paginate(page: params[:page], per_page: params[:per_page])
    respond_with @reviews, responder: ApiResponder, :status => 200
  end

  # Create a review:
  def create
    if params[:target_type] == 'JamRuby::JamTrack'
      target = JamTrack.find(params['target_id'])
    else
      target = User.find(params['target_id'])
      if params[:target_type] == 'JamRuby::Teacher'
        target = target.teacher
      end
    end

    params[:target] = target
    params[:user] = current_user

    @review = Review.create_or_update(params)

    if @review.errors.any?
      respond_with_model(@review)
      return
    end
  end

  # List reviews matching targets for given review summary:
  def details
    reviews = Review.index(:target_id => @review_summary.target_id)
    @reviews = reviews.paginate(page: params[:page], per_page: params[:per_page])
    respond_with @reviews, responder: ApiResponder, :status => 200
  end

  # Update a review:
  def update
    mods = params[:mods]
    if mods.present?
      @review.rating = mods[:rating] if mods.key?(:rating)
      @review.description = mods[:description] if mods.key?(:description)
      @review.save
    end
    respond_with_model(@review)
  end

  # Mark a review as deleted:
  def delete
    @review.deleted_at = Time.now()
    @review
    @review.save
    render :json => {}, status: 204
  end

  private

  def lookup_review_summary
    @review_summary = ReviewSummary.find(params[:review_summary_id])
  end

  def lookup_review
    arel = Review.where("id=?", params[:id])
    arel = arel.where("user_id=?", current_user) unless current_user.admin
    @review = arel.first
    raise ActiveRecord::RecordNotFound, "Couldn't find review matching #{arel}" if @review.nil?
  end
end
