# added by fq
class ForumsController < ApplicationController
  layout "users_base"
  include ApplicationHelper
  # 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,:destroy,:update,:edit]

  helper :sort
  include SortHelper

  PageLimit = 20
  def create_feedback
    if User.current.logged?
      #@memo = Memo.new(params[:memo])
      #@memo.forum_id = "1"
      #@memo.author_id = User.current.id
      #@forum = @memo.forum
      cs = CommentService.new
      @memo,message = cs.create_feedback params,User.current
      respond_to do |format|
        if !@memo.new_record?
          format.html { redirect_to forum_path(@memo.forum) }
        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
    else
      respond_to do |format|
       format.html { redirect_to signin_path }
     end
    end
  end

  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
        if params[:asset_id]
         ids = params[:asset_id].split(',')
         update_kindeditor_assets_owner ids ,@memo.id,OwnerTypeHelper::MEMO
        end
        #end
        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
        @memos
        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})
    if(params[:reorder_complex])
      @type="reorder_complex"
      @str=params[:reorder_complex]
       @forums_all = Forum.reorder("topic_count #{params[:reorder_complex]},updated_at #{params[:reorder_complex]}")
    elsif(params[:reorder_popu])
      @type="reorder_popu"
      @str=params[:reorder_popu]
      @forums_all = Forum.reorder("topic_count #{params[:reorder_popu]}")
    elsif(params[:reorder_time])
      @type="reorder_time"
      @str=params[:reorder_time]
      @forums_all = Forum.reorder("updated_at #{params[:reorder_time]}")
    else
      params[:reorder_complex] = "desc"
      @type="reorder_complex"
      @str=params[:reorder_complex]
        @forums_all = Forum.reorder("topic_count desc,updated_at desc")
    end
    @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.js
      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)"
    order = ""
    @order_str = ""
    if(params[:reorder_complex])
      order = " last_replies_memos.created_at #{params[:reorder_complex]}, #{Memo.table_name}.created_at #{params[:reorder_complex]}"
      @order_str = "reorder_complex="+params[:reorder_complex]
    elsif(params[:reorder_popu])
      order = "replies_count #{params[:reorder_popu]}"
      @order_str = "reorder_popu="+params[:reorder_popu]
    elsif(params[:reorder_time])
     order = "#{Memo.table_name}.updated_at #{params[:reorder_time]}"
     @order_str = "reorder_time="+params[:reorder_time]
    else
      order = "#{Memo.table_name}.updated_at desc"
      @order_str = "reorder_time=desc"
    end
    @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).
                    reorder(order).
                    preload(:author, {:last_reply => :author}).
                    all
    @memos
    @my_topic_count =   Memo.where("forum_id = #{@forum.id} and author_id = #{User.current.id} and parent_id is null").count
    @my_replies_count =  Memo.where("forum_id = #{@forum.id} and author_id = #{User.current.id} and parent_id is not null").count
    @errors = params[:errors]
    respond_to do |format|
      format.js
      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
    if @forum.save
      # Time 2015-03-24 17:07:05
      # Author lizanle
      # Description after save后需要进行资源记录的更新
      # owner_type = 2 对应的是 forum
      @save_flag=true
      if params[:asset_id]
        ids = params[:asset_id].split(',')
        update_kindeditor_assets_owner ids ,@forum.id,OwnerTypeHelper::FORUM
      end
      #end
      respond_to do |format|
          format.js
          format.html { redirect_to @forum, notice: l(:label_forum_create_succ) }
          format.json { render json: @forum, status: :created, location: @forum }
      end

    else
      @save_flag=false
      respond_to do |format|
        flash.now[:error] = "#{l :label_forum_create_fail}: #{@forum.errors.full_messages[0]}"
        format.js
        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.js  {render :text=> true}
        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.js { render :text=> false}
        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

  #检查forum的名字
  def check_forum_name
    forum_name_exist = true
    if params[:forum_id]
      forum_name_exist = Forum.where("name = '#{params[:forum_name]}' and id != #{params[:forum_id]}").count >= 1 ? true : false
    else
      forum_name_exist = Forum.where("name = '#{params[:forum_name]}' ").count >= 1 ? true : false
    end
    render :text => forum_name_exist
  end

  #添加论坛tag
  def add_forum_tag
    @forum = Forum.find(params[:id])
    unless @forum.nil?
      @forum.tag_list.add(params[:tag_str].split(','))
      @forum.save
    end
    respond_to do |format|
      format.js {render :delete_forum_tag}
    end
  end

  #删除forum的tag
  def delete_forum_tag
    @tag_id = (ActsAsTaggableOn::Tag.find_by_name(params[:tag_name])).id
    #forum的taggable_type = 5
    @taggings = ActsAsTaggableOn::Tagging.find_by_tag_id_and_taggable_id_and_taggable_type(@tag_id,params[:id],'Forum')

    unless @taggings.nil?
      @taggings.delete
    end

    # 是否还有其他记录 引用了 tag_id
    @tagging = ActsAsTaggableOn::Tagging.find_by_tag_id(@tag_id)
    # 如果taggings表中记录已经不存在 ，那么检查tags表 作删除动作
    if @tagging.nil?
      @tag = ActsAsTaggableOn::Tag.find_by_id(@tag_id)
      @tag.delete unless @tag.nil?
    end
    @forum = Forum.find(params[:id])
    respond_to do |format|
      format.js
    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