class Message < ApplicationRecord
  attr_accessor :total_replies_count

  belongs_to :board, counter_cache: true
  belongs_to :author, class_name: "User", foreign_key: 'author_id'
  belongs_to :parent, class_name: "Message", foreign_key: "parent_id", counter_cache: :replies_count, optional: true
  has_one :message_detail, dependent: :destroy
  accepts_nested_attributes_for :message_detail, update_only: true

  has_many :children, -> { order(updated_on: :desc ) }, class_name: "Message", foreign_key: "parent_id", dependent: :destroy
  has_many :praise_treads, as: :praise_tread_object, dependent: :destroy
  has_many :tidings, as: :container, dependent: :destroy
  has_many :attachments, as: :container, dependent: :destroy
  has_many :course_acts, :class_name => 'CourseActivity',:as =>:course_act ,:dependent => :destroy # 课程动态

  scope :root_nodes,       -> { where("parent_id IS NULL") }   #判断该信息是帖子还是回复。null为发布的帖子
  scope :reply_nodes,      -> { where("parent_id IS NOT NULL") }
  scope :visible,          -> { where(is_hidden: false)}
  scope :by_user,          ->(user) { visible if user.nil? || !user.admin? }
  scope :preload_messages, -> { includes(:author, :message_detail) }
  scope :short,            -> { select(:id, :subject, :created_on, :replies_count, :visits, :sticky, :praises_count) }
  scope :ordered,          -> (opts={}) { reorder("created_on #{opts[:sort] == 1 ? 'asc': 'desc'}") }
  scope :by_ids, lambda { |ids| where(id: ids) unless ids.blank? }
  scope :find_by_boards,   ->(ids) {where(board_id: ids)}
  scope :by_keywords, lambda { |keywords|
    where("subject LIKE ?", "%#{keywords.split(" ").join('|')}%") unless keywords.blank?
  }


  #转发表
  # has_many :forwards, as: :from, dependent: :destroy

  validates :subject, length: { maximum: 255 }

  def update_content(content)
    message_detail.update_attributes(content: content)
  end

  def copy_attachments_to_new_message(new_message, user)
    attachments.each do |attach|
      new_message.attachments << Attachment.new(attach.attributes.except("id").merge(
          quotes: 0,
          downloads: 0,
          author_id: user.id,
          created_on: Time.now
      ))
    end
  end

  def self.bulk_move_to_other_board(message_ids, to_board_id, author_id)
    message_ids.each do |id|
      message = Message.find id
      message.update_attributes(board_id: to_board_id, author_id: author_id) if message.parent_id.nil? # TODO 暂时只支持跟节点移动
    end
  end

  # 包含二级回复的总点赞数
  def total_praises_count
    praises_count + children.includes(:children).reduce(0) { |count, filed|
      sub_sum_count = filed.children.reduce(0) { |sub_count, sub_filed| sub_count += sub_filed.praises_count }
      count += filed.praises_count
      sub_sum_count += count
    }
  end

  # 包含二级回复数的总回复数
  def total_replies_count
    replies_count + children.includes(:children).reduce(0) { |count, child|
      sub_sum_count = child.children.reduce(0) { |sub_count, sub_child| sub_count += sub_child.replies_count }
      count += child.replies_count
      sub_sum_count += count
    }
  end

  def has_replies
    children.present?
  end

  #
  def by_user_with_visible(user)
    user.nil? || !user.admin? ? children.visible.limit(5) : children.limit(5)
  end

  def update_visits
    update_attributes(:visits => visits + 1)
  end
end