module AncestryWithSortedUrl
  extend ActiveSupport::Concern


  included do
    has_ancestry orphan_strategy: :restrict,
                  cache_depth: true

    acts_as_list scope: [ :ancestry ]

    before_validation :format_slug, :generate_url

    # validates_presence_of :slug, :url, unless: Proc.new { |node| node.root? }
    # validates_uniqueness_of :slug, scope: [:ancestry]

    after_commit :update_decendensts_url_if_changed
  end


private


  def format_slug
    I18n.available_locales.each do |l|
      l_key = l.to_s.downcase.sub("-", "_")
      current_slug = self.send("slug_#{l_key}")
      v = if self.root?
            l.to_s
          elsif current_slug.blank? || current_slug == "untitled"
            (self.title(locale: l) || "").parameterize
          else
            current_slug.parameterize
          end

      self.send(:slug=, v, locale: l)
    end
  end


  def generate_url
    I18n.available_locales.each do |l|
      Mobility.with_locale(l) do
        v = File.join(self.ancestors.map { |node| node.slug || "" }, self.slug || "")
        v = File.join("", v) # unless I18n.default_locale == l
        self.send(:url=, v, locale: l)
      end
    end
  end


  def update_decendensts_url_if_changed
    self.reload.descendants.find_each(&:save) if self.previous_changes[:slug].present? or self.previous_changes[:ancestry]
  end
end
