class RatingCommentController < ApplicationController
  permit "authenticated", :except => :show

  def show  
  end

  def create
    @resource = Resource.find( params[:rateable_id] )
    return if @resource.nil?
    
    respond_to do |format|
      format.html
      format.js do
        update_rating_comment
        render :update do |page|
          page.hide 'comment-form'
          page.show 'comment-action'
          page.show 'resource-reviews'
          page.insert_html :after, 'review-heading', :partial => 'resource/review', :locals => { :rating => @rating }
          page.visual_effect :highlight, "review-#{@rating.user.id}"
          page.visual_effect :highlight, 'comment-action'
          page.delay(1) do   # prevents any interaction between effect and replace_html
            page.replace_html 'comment-form-toggle', :partial => 'resource/comment_form_toggle'
            page.replace_html 'comment-form', :partial => 'resource/comment_form'
          end
        end
      end
    end
  end

  def edit
    @resource = Resource.find( params[:rateable_id] )
    return if @resource.nil?
    
    respond_to do |format|
      format.html
      format.js do
        update_rating_comment
        render :update do |page|
          page.hide 'comment-form'
          page.show 'comment-action'
          page.visual_effect :highlight, 'comment-action'
          page.replace_html 'comment-form-toggle', :partial => 'resource/comment_form_toggle'
          page.remove "review-#{@rating.user.id}"
          page.insert_html :after, 'review-heading', :partial => 'resource/review', :locals => { :rating => @rating }
          page.visual_effect :highlight, "review-#{@rating.user.id}"
        end
      end
    end
  end

  def update
  end

  def destroy
  end
  
  private
  
  def get_rating_comment
    @rating = Rating.find_by_rateable_id_and_user_id( params[:rateable_id], current_user.id )
    @rating_comment = RatingComment.find_by_rating_id_and_user_id( @rating.id, current_user.id )
  end
  
  def update_rating_comment
    @rating = Rating.find_or_create_by_rateable_type_and_rateable_id_and_user_id( 'Resource', params[:rateable_id], current_user.id )
    @rating.save if @rating.new_record?
    @rating_comment = RatingComment.find_or_create_by_rating_id_and_user_id( @rating.id, current_user.id )
    @rating_comment.rating = @rating
    @rating_comment.user = current_user
    @rating_comment.title = params[:rating_comment][:title]
    @rating_comment.comment = params[:rating_comment][:comment]
    @rating_comment.save
  end
end
