class BoardsController < ApplicationController
  before_action :require_login, :check_auth
  before_action :find_course, only: [:create]
  before_action :set_board, except: [:create]
  before_action :teacher_or_admin_allowed

  def index
    @boards = @course.boards.includes(messages: [:last_reply, :author])
  end

  def show
  end

  def create
    ActiveRecord::Base.transaction do
      board = @course.course_board
      new_board = Board.new(board_params)
      new_board.course_id = @course.id
      new_board.project_id = -1
      new_board.parent_id = board.try(:id)
      new_board.position = board.children.count + 1
      new_board.save!
    end

    normal_status(0, "添加成功")
  end

  # 子目录的拖动
  def move_category
    tip_exception("移动失败") if params[:position].blank?
    return normal_status(-1, "位置没有变化") if params[:position].to_i == @board.position

    course_board = @course.course_board
    ActiveRecord::Base.transaction do
      if params[:position].to_i < @board.position
        course_board.children.where("position < ? and position >= ?", @board.position, params[:position])
          .update_all("position = position + 1")
      else
        course_board.children.where("position > ? and position <= ?", @board.position, params[:position])
          .update_all("position = position - 1")
      end
      @board.update_attributes(position: params[:position])
    end
    normal_status(0, "移动成功")
  end

  def destroy
    ActiveRecord::Base.transaction do
      begin
        @course_board = @course.course_board
        @course_board.children.where("position > #{@board.position}").update_all("position = position - 1")
        @board.messages.update_all(board_id: @course_board.id)
        @board.destroy
      rescue Exception => e
        uid_logger_error(e.message)
        tip_exception("子目录删除失败")
        raise ActiveRecord::Rollback
      end
    end
  end

  def update
    @board.update_attributes(board_params)
    normal_status(0, "更新成功")
  end

  private

  def set_board
    @board = Board.find_by!(id: params[:id])
    @course = @board.course
  end

  def board_params
    tip_exception("子目录名称不能为空") if params[:name].blank?
    tip_exception("已存在同名讨论区") if @course.boards.exists?(name: params[:name].strip)
    params.require(:board).permit(:name)
  end
end
