class TopicsController < ApplicationController
  layout :admin_or_application_layout
  
  verify :params => "id", :only => [:edit, :approve, :hold],
         :redirect_to => { :action => "index" }
  
  before_filter :permision_required, :set_breadcrumb
   
  helper :comment
         
  # The index page shows a list of all topics
  def index   
    # @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 show
    @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_best_avg_rating
    @title                  = @topic.title

    @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

    set_default_breadcrumb
    @breadcrumb_trail << @title # can't be set in before_filter because it depends on an instance variable
    
    current_user.record_read_of @topic
  end

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

  # Admin only
  def list
    @title = "Topics - List"
    @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
    @title = "Topics - Add 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 :action => 'list'
    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
    @title = "Topics - 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 => 'list'
    end    
    @experts = Expert.find(:all)
  end

  # show a preview of the topic
  def preview
    @topic = params[:id].nil? ? Topic.new : 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 :action => 'list'
  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 :action => 'list'
  end
  
  protected
    
  # Does the current action require any specific permission?
  def action_requires_permission?
    !['index','show','archives'].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
  
  def set_breadcrumb
    super unless action_requires_permission? # use the regular one for non-admin
    set_default_breadcrumb
    if action_name == 'list'
      @breadcrumb_trail << controller_name.titleize 
    else
      @breadcrumb_trail << [controller_name.titleize, url_for(:controller => self.controller_name, :action => 'list')] << action_name.titleize
    end
  end
  
end
