class Sqm < 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|}},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 :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 "sqm#{self.id}", get_redis_hash.to_json  unless des
    redis_del "sqm#{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: "Sqm", resourceable_type: 'RouterInventory', resourceable_id: ris.pluck(:id) ).where(cms[:configurable_id].not_eq(self.id)).each(&:destroy)
    ConfigMapping.where( configurable_type: "Sqm", resourceable_type: 'LocationNetwork', resourceable_id: lns.pluck(:id) ).where(cms[:configurable_id].not_eq(self.id)).each(&:destroy)
    ConfigMapping.where( configurable_type: "Sqm", 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
    uplink = 0
    if(self.uplink == "4G")
        uplink = 4
    elsif(self.uplink == "wired")
        uplink = 1
    else
    end
    return {"ENABLE"=> self.is_enabled ? 1 : 0,"ULT" =>uplink.to_s,"DL_BW"=>self.download_speed.nil? ? (1024).to_s : (self.download_speed * 1024).to_s,"UL_BW"=>self.upload_speed.nil? ? (1000).to_s : (self.upload_speed * 1000).to_s,"QD"=>self.queuing_disciplines,"Q_S"=>self.queue_setup_script}
  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
