class BlogsController < ApplicationController
  before_filter :find_blog,:except => [:index,:create,:new,:set_homepage, :cancel_homepage]
  before_filter :find_user
  include PraiseTreadHelper

  def index
    @article = BlogComment.new

    @order, @b_sort,@type = params[:order] || 1, params[:sort] || 1, params[:type] || 1

    #确定 sort_type 1升序 2 降序
    if @order.to_i == @type.to_i
      @b_sort = @b_sort.to_i == 1 ? 2 : 1
    else
      @b_sort = 2
    end

    sort_name = "updated_at"

    sort_type = @b_sort == 1 ? "asc" : "desc"

    @topics = @user.blog.articles.reorder("#{BlogComment.table_name}.sticky desc,#{BlogComment.table_name}.#{sort_name} #{sort_type}")

    #根据 赞+回复数排序
    if @order.to_i == 2
        @type = 2

        @topics.each do |topic|
          topic[:infocount] = get_praise_num(topic) + (topic.parent ? topic.parent.children.count : topic.children.count)
          if topic[:infocount] < 0
            topic[:infocount] = 0
          end
        end

        @b_sort == 1 ? @topics = @topics.sort{|x,y| x[:infocount]  <=> y[:infocount] } : @topics = @topics.sort{|x,y| y[:infocount]  <=> x[:infocount] }

        @topics = sort_by_sticky @topics
        @topics = sortby_time_countcommon_hassticky @topics,sort_name
    else
        @type = 1
    end

    #分页
    @limit = 10
    @is_remote = true
    @atta_count = @topics.count
    @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1
    @offset ||= @atta_pages.offset
    @topics = paginateHelper @topics,@limit

    respond_to do |format|
      format.js
      format.html {render :layout=>'new_base_user'}
    end
  end
  def create

  end
  def new

  end
  def show

  end
  def update

  end
  def destory

  end
  def edit

  end

  def set_homepage
    @blog = Blog.find(params[:id])
    @blog.update_attribute(:homepage_id, params[:article_id])
    redirect_to user_path(params[:user_id])
  end

  def cancel_homepage
    @blog = Blog.find(params[:id])
    @blog.update_attribute(:homepage_id, nil)
    redirect_to user_blogs_path(params[:user_id])
  end
  private
  def find_blog
    if params[:blog_id]
      @blog = Blog.find(params[:blog_id])
    else
      render_404
    end
    if @blog.nil?
      #如果某个user的blog不存在，那么就创建一条
      @blog = Blog.create(:name=>User.find(params[:id]).realname ,
                   :description=>'',
                   :author_id=>params[:id])
    end
  end

  def find_user
    @user = User.find(params[:user_id])
  end
end
