class UpDownAlertsWorker
    include Sidekiq::Worker
    sidekiq_options :queue => :down_alerts, :retry => false, :backtrace => true
    def perform
      UpDownAlertsWorker.perform_in(3.minutes)
      alerts = Alert.joins(:alert_rules).where("alert_rules.alert_on='Device' and alert_rules.condition IN (?)", ['down']).where.not(location_network_id: nil)
      alerts.each do |alert|
        begin
         if($redis.hget("LN:DOWN:ALERT:RUN:STATUS", alert.location_network_id) != "1")
          $redis.hset("LN:DOWN:ALERT:RUN:STATUS", alert.location_network_id, "1")
          devices = alert.location_network.router_inventories.pluck(:mac_id)
          rules = alert.alert_rules
          down_devices = []
          previous_devices = []
          rules.each do |rule|
            downthreshold = (rule.value.to_i < 300) ? 300 : rule.value.to_i
            #downthreshold = rule.value.to_i
            up_devices = RouterInventory.find_up_list(devices, downthreshold, downthreshold)
            down_devices = devices - up_devices
            unless down_devices.blank?
              p "DOWN DEVICES [#{alert.location_network_id}]: #{down_devices}"
              down_devices.each do |ap_mac|
                unless alert.find_exisitng_notification(ap_mac).count > 0
                  if ($redis.hget "AP:#{ap_mac.upcase}", "hw_type") == "switch"
                    puts "CHECKING SWITCH OFFLINE STATUS"
                    check_switch_offline_status(ap_mac) ? "" : next
                    #next
                  end
                  p "DEVICES:: #{ap_mac} : #{alert.find_exisitng_notification(ap_mac).count}"
                  alert.send_notification({ap_mac_id: ap_mac}) 
                end
              end
            end
          end
          $redis.hset("LN:DOWN:ALERT:RUN:STATUS", alert.location_network_id, "0")
         end
        rescue Exception => e
          p e
          p "ALERT##{alert.id}  ---------- "+ e.backtrace.join('   ')
          $redis.hset("LN:DOWN:ALERT:RUN:STATUS", alert.location_network_id, "0")
        end
      end
    end

    def check_switch_offline_status(switch_mac_id)
      router_inventory = RouterInventory.where(mac_id: switch_mac_id).last
      location_network = router_inventory.location_network
      return false if location_network.blank?
      location_router = location_network.router_inventories.joins(:hardware_part => :hardware_category).where("hardware_categories.name" => "router").pluck(:mac_id).first
      return check_notconnected_to_router(location_router, switch_mac_id) && check_ucentral_status(router_inventory, location_network)       
    end

    def check_notconnected_to_router(location_router, switch_mac_id)
      return true if location_router.blank?
      monitoring_child = MonitoringChild.where({"info.NASID" => location_router, "created_at" => {"$gte" => (Time.now - 3.minutes), "$lt" => Time.now}}).last
      p "aaaa", monitoring_child
      return true if monitoring_child.blank?
      return true if monitoring_child.clients.select{|x| x["MAC"].downcase == switch_mac_id.downcase}.blank?
      return false
    end

    def check_ucentral_status(router_inventory, location_network)
      udevicestatus = call_commands_api(location_network, router_inventory)
      return false if udevicestatus.blank?
      return false if udevicestatus.has_key?("connected") && udevicestatus["connected"] == true
      return true if udevicestatus.has_key?("connected") && udevicestatus["connected"] == false
      return false
    end

    def call_commands_api(location_network, router_inventory)
      res = OpenWifi::ProvisioningService.new(location_network, location_network.organisation, router_inventory.mac_id).get_device_status(router_inventory.mac_id)
      p res
      res
    rescue => e
      p "Error fetching commands API: #{e.message}"
      {}
    end
  end
