  class HbWorker
  include Sidekiq::Worker
  sidekiq_options :queue => :hb_monitoring, :retry => false, :backtrace => true

  def perform(message)
    # message = $redis.lpop('bravo')
    unless message.blank?
      message = message.to_json
      #Add data to monitoring capped collection
      MonitoringDataCapped.save_hb(message)

      mc = MonitoringChild.save_hb(message)
      ap_details = $redis.hgetall "AP:#{mc.info['NASID']}"
      last_hb = ap_details["last_hb"]
      if mc.info["FIRST_HB"] == 1
         hb_freq = ap_details['hb_freq']
         interval = RouterInventory.get_hb_intreval(hb_freq)
        if last_hb.present? && (mc.created_at.to_i - last_hb.to_i) >= interval
          ApDowntime.create( mac: mc.info['NASID'], st: Time.zone.at(last_hb.to_i), et: mc.created_at, sec: (mc.created_at.to_i - last_hb.to_i))
        end
      end
      #Set redis last HB time
      ap_details = $redis.hgetall "AP:#{mc.info['NASID']}"
      #$redis.multi do
        $redis.hset "AP:#{mc.info['NASID']}", "prev_last_hb", last_hb
        $redis.hset "AP:#{mc.info['NASID']}", "last_hb", mc.created_at.to_i
        $redis.hset "AP:#{mc.info['NASID']}", "version", mc.info["PIAP_VERSION"] if ap_details["version"].blank? || ap_details["version"] != mc.info["PIAP_VERSION"] || mc.info["FIRST_HB"] == 1
        $redis.hset "AP:#{mc.info['NASID']}", "p_version", ap_details["version"] if ap_details["version"] != mc.info["PIAP_VERSION"] && mc.info["FIRST_HB"] == 1
        $redis.hset "AP:#{mc.info['NASID']}", "pub_ip", mc.s_info["PUBLIC_IP"] if ap_details["pub_ip"].blank? || ap_details["pub_ip"] != mc.info["PUBLIC_IP"]  || mc.info["FIRST_HB"] == 1
        if mc.radio != nil
          mc.radio.each do |radio|
            if radio['BAND'].to_s == '1'
              $redis.hset "AP:#{mc.info['NASID']}", "C_24GHZ" , radio['CHANNEL']
              $redis.hset "AP:#{mc.info['NASID']}", "P_24GHZ" , radio['TXPOWER']
            else
              $redis.hset "AP:#{mc.info['NASID']}", "C_5GHZ" , radio['CHANNEL']
              $redis.hset "AP:#{mc.info['NASID']}", "P_5GHZ" , radio['TXPOWER']
            end
          end
        end
      #end
      if (mc.info["FIRST_HB"] == 1 || ap_details['hw_part_no'].blank?) && mc.info["HW_PART_NO"].present? && mc.info["HW_PART_NO"] != ""# && !mc.info["HW_PART_NO"].nil?
        ri = RouterInventory.find_by_mac_id mc.info['NASID']
        ri.set_hw_part_no mc.info["HW_PART_NO"] if ri.present? && ri.hardware_part_id.blank?
      end
      if ap_details['alert'] == "1"
        #Create Alerts worker
        jid=AlertsWorker.perform_async(message, mc.created_at.to_i)

        puts "Heartbeat worker completed --- Alerts Worker #{jid}"
      end

    end
  end
end
