# == Schema Information
#
# Table name: portforwarding_groups
#
#  id                  :integer          not null, primary key
#  group_name          :string(255)
#  organisation_id     :integer
#  router_inventory_id :integer
#  location_network_id :integer
#  created_at          :datetime
#  updated_at          :datetime
#  tagging_lists       :text
#

class PortforwardingGroup < ActiveRecord::Base
  resourcify
  include PublicActivity::Model

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

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

  include AssociatedResource
  include RedisWrapper
  has_many :port_forwardings, :dependent => :destroy
  belongs_to :organisation
  belongs_to :router_inventory
  belongs_to :location_network
  accepts_nested_attributes_for :port_forwardings, :allow_destroy => true
  has_many :pf_inventories, :dependent => :destroy
  has_many :router_inventories_old, :through => :pf_inventories

  def update_redis
    unless self.blank?
      set_redis
      lns = self.location_networks
      tags = self.tags.map(&:name)
      routers =  RouterInventory.where(location_network_id: lns.pluck(:id)) + RouterInventory.tagged_with(tags)  + self.router_inventories
      (routers.uniq || []).each{|x| x.update_redis}
    end
  end

  def set_redis
      return if  self.port_forwardings.blank?
      pf = []
      self.port_forwardings.each do |x|
        pf << {"PROTO"=> x.protocol,"ORIG_IP"=>x.ip_address,"ORIG_PORT"=>x.external_port,"FWD_IP"=>x.ip_address,"FWD_PORT"=>x.internal_port}.to_json
      end
      redis_set "portfw#{self.id}", pf.to_json
  end

  after_create do |x|
    x.update_redis
  end

  after_update do |x|
    x.update_redis
  end

  after_destroy do |x|
    redis_del "portfw#{x.id}"
  end
end
