# frozen_string_literal: true

module Litany
  # Adds the ability to set meta data on the resource hierarchy, currently utilized by userdata.
  module Metable
    def compile_metas
      metas = resource_tree.collect(&:metas)
      # TODO: should move out into it's own modules thing
      chef_attributes = resource_tree.find_all { |resource| resource.is_a?(ServiceRoot) || resource.is_a?(Project) }.collect(&:chef_attributes).reduce(:deep_merge)
      metas << { chef_attributes: { Key: :chef_attributes, Value: chef_attributes } } unless chef_attributes.empty?
      metas.reduce(:merge).map { |_, e| { e[:Key] => e[:Value] } }.reduce(:merge) || {}
    end

    def meta(key, value)
      metas[key.downcase.to_sym] = { Key: key.to_sym, Value: value }
    end

    def metas
      @metas ||= {}
    end
  end
end
