class TalkController < ApplicationController
  before_filter :permision_required
  
  verify :params => "topic_id",
         :redirect_to => { :controller => "topics" },
         :except => [:remove_comment, :mark]
  
  helper :comment, :topics
    
  # retrieve the 'new comment' form
  def get_comment_form
    topic = Topic.find(params[:topic_id])
    
    @comment = topic.comments.build(params[:comment])
    @comment.parent_id = params[:parent_id].to_i
    
  end

  # create a new comment
  def comment
    topic = Topic.find(params[:topic_id])

    @comment = topic.comments.build(params[:comment])

    if CommentSpecification::passes_all?(@comment.subject, current_user) && params[:save]=='1' && @comment.save 
      render :action => 'new_comment'                
    else # didn't save properly
      CommentSpecification.failures.each{|failure| @comment.errors.add_to_base(failure)}
      logger.info "failed to save new comment because of #{@comment.errors.full_messages}"
      render :action => 'preview'      
    end
    
  end
  
  # mark the given comment as read
  def mark
    current_user.record_read_of Comment.find(params[:id])
    render :nothing => true
  end  
  
  # Admim can flag a comment as inapropriate. The comment will no longer be visible to participants
  def remove_comment
    @comment = Comment.find(params[:id])
    @comment.update_attribute(:removed, true)
    respond_to do |type|
      type.html do
        flash[:notice] = "Comment removed"
        redirect_to :back
      end
      type.js
    end
    
  end
  
  private
  
  # remove_comment requiers permission
  def action_requires_permission?
    ['remove_comment'].include?(action_name)
  end
end
