class RaterController < ApplicationController

  # Depending on the type of request, respond differently.
  # Regular (GET) requests are given a redirection (back)
  # While XHR requests respond by returning the updated rating widget
  def create
    check_valid_rating_type

    rating_class = params[:rating_type].camelize.constantize
    subject      = rating_class.subject_class.find(params[:subject_id])
    
    @rating = RatingSpecification::passes_all?(subject, current_user, rating_class) ?
      rating_class.create(:subject => subject, :user => current_user, :value => params[:value]) :
      AbstractRating.new
    
    if @rating && !@rating.new_record?
      # rating exists, and was saved (validation passed)     
      logger.debug "Rating created: #{@rating.attributes.to_yaml}"
      
      @element_id = "#{@rating.class.to_s.underscore}_for_#{@rating.subject.id}"
      
      respond_to do |type|
        type.html do
          flash[:javascript] = %q{urchinTracker("/funnel/rating/success?type=%s&amp;id=%d")} % [@rating.subject.class, @rating.subject.id]
          redirect_to :back 
        end
        type.js { render :action => 'update_comment' }
      end # respond_to
        
    else
      # a response for Spec failure and Rating save failure
      @rating.errors.add_to_base(RatingSpecification::failures)
      logger.debug "Rating failures: #{@rating.errors.full_messages.to_yaml}"
      
      respond_to do |type|
        type.html do
          flash[:alert] = "Not allowed"
          redirect_to :action => "index" 
        end
        type.js do 
          render :update do |page|
            message = @rating.errors.full_messages.join("\\n- ")
            page <<  %q{urchinTracker("/funnel/rating/failure")}
            page << "alert('Not allowed\\n- #{message}');"
          end
        end
      end
    end
  end
  
  private
  
  def check_valid_rating_type
    raise "illegal type" unless params[:rating_type].camelize.constantize.new.is_a? AbstractRating
  end
  
end
