class TopicsController < ApplicationController

  verify :params => "id", :only => [:edit, :approve, :hold],
         :redirect_to => { :action => "index" }

  # RSS gets special treatment -- TODO move RSS to it's own controller
  session :off, :only => :rss  
  before_filter      :permision_required,               :except => :rss
  skip_before_filter :setup_userstamp, 
                     :login_required, 
                     :logout_suspended_users, :only   => :rss
  
  helper :comment
         
  # The index page shows a list of all topics
  def index   
    # show todays news, introduce todays topic and list previous topics
    #flash.now[:notice] = 'test notice'
    #flash.now[:alert] = 'test alert'
    @news   = Snippet.find_or_create_by_name('news')
    @topics = current_user.topics_find(:all, :order => '`start_date` DESC', :limit => 5)
    @topic  = current_user.topics_find(:first, :conditions =>['start_date = ?',Date.today])
  end

  def rss
    @feed_title       = Settings.consultation_name
    @feed_link        = Settings.application_url
    @feed_description = Settings.consultation_description
    @topics           = Guest.new.topics_find(:all, :order => '`start_date` DESC')
    render :layout => false
  end
  
  def show
    # @topic                  = current_user.topics_find(params[:id], :include => {:comments => [{:ratings => :user}, :user] } )
    # @topic                  = current_user.topics_find(params[:id], :include => {:comments => [{:ratings => :user}, :user] } )
    #@topic                  = current_user.topics_find(params[:id])
    @topic                  = current_user.topics_find(params[:id], :include => [:expert, :support_materials] )
    @topic_comments         = @topic.comments.thread_starters
    @most_read_comments     = @topic.comments.find_three_most_read
    @highest_rated_comments = @topic.comments.find_three_highest_avg_rating
    @title                  = "%s (%s)" % [@topic.title, @topic.start_date]
    #render :nothing => true

    @topic_all_comments_by_id  = {}
    @all_comments = @topic.comments.find(:all, :include =>  [{:ratings => :user}, :user] )
    @all_comments.each do |c| 
      @topic_all_comments_by_id[c.id] = c
    end
    
    @topic_all_comment_children_ids = Comment.all_parent_children_ids(@all_comments.collect(&:id))
    @topic_comment_count =  @topic.comments.count_visible
  end

  def archives
    @full_list_of_topics = current_user.topics_find(:all, :order => '`start_date` DESC')
  end

  # TODO:
  # Allow a topic to be created with a conflicting date
  # but require the user to "force" the save

  # Create a new Topic
  def new
    @topic = Topic.new(params[:topic])
    @topic.expert = current_user unless current_user.has_permission_to?(:topics_change_expert)
    if request.post? && @topic.save
      flash[:notice] = "New Topic created"
      add_flash_message_if_date_already_taken(@topic)
      redirect_to '/'
    end
    @experts = Expert.find(:all)
  end
  
  # Edit a topic. Change the content, except for the author (stays as creator)
  # Restricted to Editor and Admin
  def edit
    @topic = current_user.topics_find(params[:id])
    @topic.attributes = params[:topic]
    if request.post? && @topic.save
      flash[:notice] = "Topic updated"
      add_flash_message_if_date_already_taken(@topic)
      redirect_to :action => 'show', :id => @topic.id
    end    
    @experts = Expert.find(:all)
  end

  # show a preview of the topic
  def preview
    @topic = current_user.topics_find(params[:id])
    @topic.attributes = params[:topic]
    render :layout => false
  end
  
  
  # Set the approved flag of a topic to TRUE
  # Restricted to Admin
  def approve
    current_user.topics_find(params[:id]).update_attribute(:approved, true)
    flash[:notice] = "Topic approved" 
    redirect_to '/'
  end
  
  # Set the approved flag of a topic to FALSE
  # Restricted to Admin
  def hold
    current_user.topics_find(params[:id]).update_attribute(:approved, false)
    flash[:notice] = "Topic put on hold"
    redirect_to '/'
  end
  
  protected
    
  # Does the current action require any specific permission?
  def action_requires_permission?
    ['edit','new','approve', 'hold', 'preview'].include?(action_name)
  end
  
  def add_flash_message_if_date_already_taken(topic)
    # TODO: this logic should be in Topic. eg. Topic::dates_available?(@topic) or @topic.dates_available?
    flash[:alert] = "Another topic is already scheduled for that day" if Topic.find(:first, :conditions => ['`start_date` = ? AND id != ?', topic.start_date, topic.id])    
  end
end
