class LibraryController < ApplicationController
  layout :admin_or_application_layout
  before_filter :permision_required, :set_breadcrumb

  verify :params => "id",
         :except => [:index, :list],
         :add_flash => { :alert => "Missing required information" },
         :redirect_to => { :action => :list }
  
  def index 
    @topics = current_user.topics_find(:all, :order => 'start_date DESC', :include => :support_materials)
  end
  
  # like index, but for admins
  def list
    @topics = current_user.topics_find(:all, :order => 'start_date DESC', :include => :support_materials)    
    render :action => 'index'
  end
  
  def list_for_topic
    @topic = Topic.find(params[:id])
    @title = "Support Material for '%s'" % @topic.title
  end
  
  def new
    topic = Topic.find(params[:id])
    @support_material = topic.support_materials.build(params[:support_material])
    if request.post? && @support_material.save
      flash[:notice] = 'Support Material Created'
      redirect_to :action => 'list_for_topic', :id => @support_material.topic.id
    end      
  end

  def edit
    @support_material = SupportMaterial.find(params[:id])
    @support_material.attributes = params[:support_material]
    if request.post? && @support_material.save
      flash[:notice] = "Support Material updated"
      redirect_to :action => 'list_for_topic', :id => @support_material.topic.id
    end    
  end
  
  def remove
    sup = SupportMaterial.find(params[:id])
    topic_id = sup.topic.id
    begin
      if sup.destroy
        flash[:notice] = 'Support Material Removed'
      end
    rescue
      flash[:alert] = "There was a problem removing that Support Matrial"
    end
    redirect_to :action => 'list_for_topic', :id => topic_id
  end
  
  private
  
  def action_requires_permission?
    action_name != 'index'
  end
end
