# == Schema Information
#
# Table name: firewall_configs
#
#  id                  :integer          not null, primary key
#  name                :string(255)
#  location_network_id :string(255)
#  created_at          :datetime
#  updated_at          :datetime
#

class FirewallConfig < ActiveRecord::Base
  #resourcify
  include AssociatedResource
  include RedisWrapper
  include PublicActivity::Model
  belongs_to :location_network
  has_many :client_communications,:dependent => :destroy
  has_many :router_inventories, through: :config_mappings, source: :resourceable, source_type: "RouterInventory"
  has_many :location_networks, through: :config_mappings, source: :resourceable, source_type: "LocationNetwork"
  accepts_nested_attributes_for :client_communications ,:allow_destroy => true

  tracked owner: ->(controller, model) { controller && controller.tracked_current_user },params:
  { :attributes => proc {|controller, model_instance| {"firewall_config(#{model_instance.name})" => model_instance.changes}}},organisation_id: ->(controller, model) { controller && controller.tracked_current_user.organisation_id }, :location_network_id => proc {|controller, model_instance|model_instance.location_network_id}

  tracked assumed_by: proc {|controller, model| controller.user_assumed_by if controller}

  def update_redis
    ris = self.router_inventories
    lns = self.location_networks
    routers = RouterInventory.where(location_network_id: lns.pluck(:id)) + ris
    #remove previous config association
    cms = ConfigMapping.arel_table
    ConfigMapping.where( configurable_type: "FirewallConfig", resourceable_type: 'RouterInventory', resourceable_id: ris.pluck(:id) ).where(cms[:configurable_id].not_eq(self.id)).each(&:destroy)
    ConfigMapping.where( configurable_type: "FirewallConfig", resourceable_type: 'LocationNetwork', resourceable_id: lns.pluck(:id) ).where(cms[:configurable_id].not_eq(self.id)).each(&:destroy)
    routers = RouterInventory.where(id: ris.pluck(:id))  + RouterInventory.where(location_network_id: lns.pluck(:id))
    (routers.uniq||[]).each do |y|
      y.update_redis unless y.blank?
    end
  end

  after_create do |x|
    x.update_redis
  end

  after_update do |x|
    x.update_redis
  end

  after_destroy do |x|
    x.update_redis
  end

end
