module ForumSupport
  module Categories
    def self.included(base)
      base.before_filter :find_category, :only => [:show, :edit, :update, :destroy]
      base.authorize_resource :class => TopicCategory, :instance_name => :category

      base.builtin_template_scope = 'forum/categories'
    end

    def index
      @categories = @forum.categories :include => :topics

      render 'forums/categories/index'
    end

    def show
      @topics = @category.topics.paginate(:page => params[:page])
      @topic  = @category.topics.build

      render 'forums/categories/show'
    end

    def new
      @category = @forum.categories.build

      render 'forums/categories/new'
    end

    def create
      @category = @forum.categories.build(params[:topic_category])

      if @category.save
        flash[:notice] = "Category was successfully created."
        redirect_to forum_url
      else
        render 'forums/categories/new'
      end
    end

    def edit
      render 'forums/categories/edit'
    end

    def update
      if @category.update_attributes(params[:topic_category])
        flash[:notice] = "Category was successfully updated."
        redirect_to forum_url
      else
        render 'forums/categories/edit'
      end
    end

    def destroy
      @category.destroy

      flash[:notice] = "Category was successfully deleted."
      redirect_to forum_url
    end

    private

    def find_category
      @category = @forum.categories.find(params[:id])
    end
  end
end
