class Library < ApplicationRecord
  include AASM

  belongs_to :user
  belongs_to :cover, class_name: 'Attachment', foreign_key: :cover_id, optional: true
  belongs_to :laboratory, optional: true

  has_many :library_applies, dependent: :delete_all
  has_many :library_library_tags, dependent: :delete_all
  has_many :library_tags, through: :library_library_tags

  has_many :attachments, as: :container
  has_one :praise_tread_cache, foreign_key: :object_id
  has_many :praise_treads, as: :praise_tread_object, dependent: :destroy

  validates :content, length: { maximum: 5000, too_long: "不能超过5000个字符" }

  validates :uuid, presence: true, uniqueness: true

  aasm(:status) do
    state :pending, initial: true
    state :processing
    state :refused
    state :published

    event :submit do
      transitions from: [:pending, :refused], to: :processing
    end

    event :refuse do
      transitions from: :processing, to: :refused
    end

    event :publish do
      transitions from: :processing, to: :published
    end
  end

  before_save :set_laboratory
  private def set_laboratory
    return unless new_record?

    self.laboratory = Laboratory.current if laboratory_id.blank?
  end

  def increment_visited_count!(num = 1)
    increment_column!(:visited_count, num)
  end

  def generate_uuid
    uuid = Util::UUID.time_uuid
    while Library.exists?(uuid: uuid)
      uuid = Util::UUID.time_uuid
    end

    self.uuid = uuid
  end

  private

  def increment_column!(column, num = 1)
    self.class.connection.execute("update #{self.class.table_name} set #{column} = COALESCE(#{column}, 0) + #{num} where id = #{id}")
  end
end