class CommentsController < ApplicationController
  before_action :find_hack
  before_action :require_login


  # 评论
  def create
    begin
      @discuss = @hack.discusses.new(comment_params) # 管理员回复的能够显示
      @discuss.hidden = false
      @discuss.user_id = current_user.id
      @discuss.save!
    rescue Exception => e
      uid_logger_error("create discuss failed : #{e.message}")
      render_error("评论异常")
    end
  end

  # 回复
  def reply
    begin
      @discuss = @hack.discusses.new(reply_params)
      @discuss.hidden = false
      @discuss.user_id = current_user.id
      @discuss.root_id = params[:parent_id]
      @discuss.save!
    rescue Exception => e
      uid_logger_error("reply discuss failed : #{e.message}")
      render_error("回复评论异常")
    end
  end

  # 列表
  def index
    disscusses = @hack.disscusses.where(:root_id => nil)
    @disscuss_count = disscusses.count
    @disscusses= paginate disscusses
  end

  # 删除
  def destroy
    @hack.discusses.find_by(id: params[:id]).destroy
    render_ok
  end


  private
  def find_hack
    @hack = Hack.find_by_identifier params[:identifier]
  end

  def comment_params
    params.require(:comments).permit(:content)
  end

  def reply_params
    params.require(:comments).permit(:content, :parent_id)
  end
end