# Categories
class Category < ApplicationRecord
  extend FriendlyId
  extend ActsAsTree::TreeWalker
  include FriendlyFinder

  acts_as_tree order: 'name'
  friendly_id :name, use: :slugged
  has_and_belongs_to_many :products
  has_one :image, as: :imageable, dependent: :destroy

  validates :name, presence: true

  after_update :a_update

  def should_generate_new_friendly_id?
    slug.blank? || will_save_change_to_attribute?(:name)
  end

  def created_name
    Admin.find(updated_by).description
  end

  def created_date
    updated_at.to_date
  end

  def active_products
    products.where('active = 1').order('name ASC')
  end

  def active_childrens
    Category.where(parent_id: id, active: true).order('name ASC')
  end

  def a_update
    return unless saved_change_to_attribute?(:slug)
    # preprocess images
    image.change_filename(attribute_before_last_save(:slug), slug)
  end

  # returns image of category, if category don't have own image returns first
  # product cover image
  def cover_image
    im = image
    if im.blank?
      pr = active_products.first
      im = pr.cover_image unless pr.blank?
    end
    im
  end
end
