module AssociatedResource
  extend ActiveSupport::Concern

  included do
    attr_accessor :associated_resources

    has_many :config_mappings, as: :configurable, dependent: :destroy
    has_many :location_networks, through: :config_mappings, source: :resourceable, source_type: 'LocationNetwork'
    has_many :router_inventories, through: :config_mappings, source: :resourceable, source_type: 'RouterInventory'
    has_many :tags, through: :config_mappings, source: :resourceable, source_type: "ActsAsTaggableOn::Tag", class_name: 'ActsAsTaggableOn::Tag'

    def associated_resources
      arr = []
      self.config_mappings.each do |config|
        case config.resourceable_type
        when "LocationNetwork"
          arr << "network:#{config.resourceable_id}"
        when "RouterInventory"
          arr << "AP:#{config.resourceable_id}"
        when "ActsAsTaggableOn::Tag"
          arr << "tag:#{config.resourceable_id}"
        end
      end

      arr
    end

    def associated_resources=(value)
      attribute_will_change!('associated_resources') if associated_resources != value
      resource_mapping = ConfigMapping::RESOURCE_MAP
      value.delete("")
      exisiting_config = self.associated_resources
      new_config = value - exisiting_config
      config_to_remove = exisiting_config - (exisiting_config & value)
      new_config.each do |n|
        self.config_mappings.build( resourceable_type: resource_mapping[n.split(':')[0]], resourceable_id: n.split(':')[1].to_i )
      end
      config_to_remove.each do |n|
        self.config_mappings.where( resourceable_type: resource_mapping[n.split(':')[0]], resourceable_id: n.split(':')[1].to_i ).each(&:destroy)
      end
    end
  end
end
