class Library < ApplicationRecord
  include AASM

  belongs_to :user
  belongs_to :cover, class_name: 'Attachment', foreign_key: :cover_id, 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 :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

  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