# added by fq
class ForumsController < ApplicationController
  layout "users_base"

  # GET /forums
  # GET /forums.json
  before_filter :find_forum_if_available
  before_filter :authenticate_user_edit, :only => [:edit, :update]
  before_filter :authenticate_user_destroy, :only => [:destroy]
  before_filter :require_login, :only => [:new, :create]

  helper :sort
  include SortHelper

  PageLimit = 20

  def create_memo
    @memo = Memo.new(params[:memo])
    @memo.forum_id = @forum.id
    @memo.author_id = User.current.id

    @memo.save_attachments(params[:attachments] || (params[:memo] && params[:memo][:uploads]))

    respond_to do |format|
      if @memo.save
        format.html { redirect_to (forum_memo_url(@forum, (@memo.parent_id.nil? ? @memo : @memo.parent_id))), notice: "#{l :label_memo_create_succ}" }
        format.json { render json: @memo, status: :created, location: @memo }
      else
        sort_init 'updated_at', 'desc'
        sort_update 'created_at' => "#{Memo.table_name}.created_at",
                    'replies' => "#{Memo.table_name}.replies_count",
                    'updated_at' => "COALESCE (last_replies_memos.created_at, #{Memo.table_name}.created_at)"

        @topic_count = @forum.topics.count
        @topic_pages = Paginator.new @topic_count, per_page_option, params['page']
        @memos = @forum.topics.
                        reorder("#{Memo.table_name}.sticky DESC").
                        includes(:last_reply).
                        limit(@topic_pages.per_page).
                        offset(@topic_pages.offset).
                        order(sort_clause).
                        preload(:author, {:last_reply => :author}).
                        all

        flash.now[:error] = "#{l :label_memo_create_fail}: #{@memo.errors.full_messages[0]}"
        # back_error_page = @memo.parent_id.nil? ? forum_path(@forum) : forum_memo_path(@forum, @memo.parent_id)
        format.html { render action: :show, layout: 'base_forums' }#, error: "#{l :label_memo_create_fail}: #{@memo.errors.full_messages[0]}" }
        format.json { render json: @memo.errors, status: :unprocessable_entity }
      end
    end
  end
  
  def index
    @offset, @limit = api_offset_and_limit({:limit => 10})
    @forums_all = Forum.reorder("sticky DESC")
    @forums_count = @forums_all.count
    @forums_pages = Paginator.new @forums_count, @limit, params['page']


    @offset ||= @forums_pages.offset
     @forums = @forums_all.offset(@offset).limit(@limit).all
    #@forums = Forum.all
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @forums }
    end
  end

  # GET /forums/1
  # GET /forums/1.json
  def show
    sort_init 'updated_at', 'desc'
    sort_update 'created_at' => "#{Memo.table_name}.created_at",
                'replies' => "#{Memo.table_name}.replies_count",
                'updated_at' => "COALESCE (last_replies_memos.created_at, #{Memo.table_name}.created_at)"

    @memo = Memo.new(:forum => @forum)
    @topic_count = @forum.topics.count
    @topic_pages = Paginator.new @topic_count, per_page_option, params['page']
    @memos = @forum.topics.
                    reorder("#{Memo.table_name}.sticky DESC").
                    includes(:last_reply).
                    limit(@topic_pages.per_page).
                    offset(@topic_pages.offset).
                    order(sort_clause).
                    preload(:author, {:last_reply => :author}).
                    all



    # @offset, @limit = api_offset_and_limit({:limit => 10})
    # @forum = Forum.find(params[:id])
    # @memos_all = @forum.topics
    # @topic_count = @memos_all.count
    # @topic_pages = Paginator.new @topic_count, @limit, params['page']
    
    # @offset ||= @topic_pages.offset
    # @memos = @memos_all.offset(@offset).limit(@limit).all
    respond_to do |format|
      format.html {
        render :layout => 'base_forums'
      }# show.html.erb
      format.json { render json: @forum }
    end
  end

  # GET /forums/new
  # GET /forums/new.json
  def new
    @forum = Forum.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @forum }
    end
  end

  # GET /forums/1/edit
  def edit
    @forum = Forum.find(params[:id])
  end

  # POST /forums
  # POST /forums.json
  def create
    @forum = Forum.new(params[:forum])
    @forum.creator_id = User.current.id

    respond_to do |format|
      if @forum.save
        format.html { redirect_to @forum, notice: l(:label_forum_create_succ) }
        format.json { render json: @forum, status: :created, location: @forum }
      else
        flash.now[:error] = "#{l :label_forum_create_fail}: #{@forum.errors.full_messages[0]}"
        format.html { render action: "new" }
        format.json { render json: @forum.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /forums/1
  # PUT /forums/1.json
  def update
    @forum = Forum.find(params[:id])

    respond_to do |format|
      if @forum.update_attributes(params[:forum])
        format.html { redirect_to @forum, notice: l(:label_forum_update_succ) }
        format.json { head :no_content }
      else
        flash.now[:error] = "#{l :label_forum_update_fail}: #{@forum.errors.full_messages[0]}"
        format.html { render action: "edit" }
        format.json { render json: @forum.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /forums/1
  # DELETE /forums/1.json
  def destroy
    @forum = Forum.find(params[:id])
    @forum.destroy

    respond_to do |format|
      format.html { redirect_to forums_url }
      format.json { head :no_content }
    end
  end

  def search_forum
    # @forums = paginateHelper Forum.where("name LIKE '%#{params[:name]}%'")
    q = "%#{params[:name].strip}%"
    (redirect_to forums_url, :notice => l(:label_sumbit_empty);return) if params[:name].blank?
    @offset, @limit = api_offset_and_limit({:limit => 10})
    @forums_all = Forum.where("name LIKE ?", q)
    @forums_count = @forums_all.count
    @forums_pages = Paginator.new @forums_count, @limit, params['page']


    @offset ||= @forums_pages.offset
    @forums = @forums_all.offset(@offset).limit(@limit).all
    respond_to do |format|
      format.html {
        render 'index'
      }
      format.json { render json: @forums }
    end
  end

  def search_memo
    q = "%#{params[:name].strip}%"

    limit = PageLimit
    @memo = Memo.new
    @offset, @limit = api_offset_and_limit({:limit => limit})
    @forum = Forum.find(params[:id])
    @memos_all = @forum.topics.where("subject LIKE ?", q)
    @topic_count = @memos_all.count
    @topic_pages = Paginator.new @topic_count, @limit, params['page']
    
    @offset ||= @topic_pages.offset
    @memos = @memos_all.offset(@offset).limit(@limit).all
    respond_to do |format|
      format.html {
        render 'show', :layout => 'base_forums'
      }
      format.json { render json: @forum }
    end 
  end



  private


  def find_forum_if_available
    @forum = Forum.find(params[:id]) if params[:id]
  rescue ActiveRecord::RecordNotFound
    render_404
    nil
  end

  def authenticate_user_edit
    find_forum_if_available
    render_403 unless @forum.editable_by? User.current
  end

  def authenticate_user_destroy
    find_forum_if_available
    render_403 unless @forum.destroyable_by? User.current
  end
end