class Discuss < ApplicationRecord
  default_scope { order(created_at: :desc) }

  belongs_to :user
  belongs_to :parent, class_name: 'Discuss', foreign_key: :parent_id, optional: true

  has_many :children, -> { reorder(created_at: :asc) }, class_name: 'Discuss', foreign_key: :parent_id
  has_many :praise_treads, as: :praise_tread_object, dependent: :destroy
  has_many :tidings, as: :container, dependent: :destroy
  has_one :praise_tread_cache, as: :object, dependent: :destroy
  belongs_to :dis, polymorphic: true

  belongs_to :challenge
  after_create :send_tiding

  scope :children, -> (discuss_id){ where(parent_id: discuss_id).includes(:user).reorder(created_at: :asc) }

  def has_parent?
    parent_id.present?
  end

  def username
    user.full_name
  end

  def can_deleted?(user)
    user.admin? || user.id == user_id
  end

  def game_url(shixun, user)
    return '' unless shixun.has_manager?(user)

    game = Game.joins(:challenge).where(challenges: { shixun_id: shixun.id, position: position || 1 })
             .select(:identifier).find_by(user_id: user_id)
    "/tasks/#{game&.identifier}"
  end

  # def contents(shixun, user)
  #   return content unless hidden?
  #
  #   shixun.has_manager?(user) ? content : ''
  # end

  def child_discuss(user)
    Discuss.where(parent_id: self.id).includes(:user).reorder(created_at: :asc)
  end

  def child_discuss_count
    Discuss.where(root_id: id).count
  end

  private

  def send_tiding
    base_attrs = {
      trigger_user_id: user_id, parent_container_id: challenge_id, parent_container_type: 'Challenge',
      belong_container_id: dis_id, belong_container_type: 'Shixun', viewed: 0, tiding_type: 'Comment'
    }
    user_id = has_parent? ? parent.user_id : Challenge.find(challenge_id).user_id
    tidings.create!(base_attrs.merge(user_id: user_id))
  end
end
