# == Schema Information
#
# Table name: snmp_configs
#
#  id                  :integer          not null, primary key
#  router_inventory_id :integer
#  location_network_id :integer
#  organisation_id     :integer
#  server_ip           :string(255)
#  server_port         :string(255)
#  server_community    :string(255)
#  ro_community        :string(255)
#  rw_community        :string(255)
#  created_at          :datetime
#  updated_at          :datetime
#  tagging_lists       :text
#

class SnmpConfig < ActiveRecord::Base
  resourcify
  include AssociatedResource
  include RedisWrapper
  include PublicActivity::Model

  tracked owner: ->(controller, model) { controller && controller.tracked_current_user },params: { :attributes => proc {|controller, model_instance| {"snmp_configuration(#{model_instance.server_ip})" => 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}
  
  belongs_to :location_network
 # belongs_to :router_inventory
  belongs_to :organisation

  def self.tagging_lists(lists)
    ar=[]
    arr = lists.split("&&") unless lists.blank?
    (arr || []).each do |y|
      res = y.split("--")
      ar.push({"id"=>res[0]+"--"+res[1],"name"=>res[2]})
    end
    return ar
  end

  def set_redis(des=false)
    redis_set "snmp#{self.id}", get_redis_hash.to_json  unless des
    redis_del "snmp#{self.id}" if des
  end

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

  def get_redis_hash
    return {"SERVER_IP"=> self.server_ip,"SERVER_PORT"=>self.server_port,"SERVER_COMMUNITY"=>self.server_community,"RO_COMMUNITY"=>self.ro_community,"RW_COMMUNITY"=>self.rw_community}

  end

  after_create do |x|
    x.update_configuration
  end

  after_update do |x|
    x.update_configuration
  end

  after_destroy do |x|
    x.update_configuration(true)
  end
end
