                                                                   
class ClientSession
  include Mongoid::Document

  field :access_point, type: String
  field :ip, type: String
  field :mac, type: String
  field :hostname, type: String
  field :device_type, type: String
  field :s_t, type: Date
  field :e_t, type: Date
  field :d, type: Date


  index({"access_point" => 1, "ip" => 1, "mac" => 1}, { background: true })

  CRIT_LVL = {1 => "Non Critical", 2 => " Critical Low", 3 => "Critical High"}
   def self.save_data data
    cs = self.new
    cs.access_point = data[:access_point]
    cs.ip = data[:ip]
    cs.mac = data[:mac]
    cs.hostname = data[:hostname]
    cs.device_type = data[:device_type]
    cs.s_t = data[:s_t]
    cs.e_t = data[:e_t]
    cs.d = Time.zone.now.utc
    cs.save
   end

   def self.update_data obj, data
    cs = obj
    # cs.access_point = data[:access_point]
    # cs.ip = data[:ip]
    # cs.mac = data[:mac]
    # cs.hostname = data[:hostname]
    # cs.device_type = data[:device_type]
    # cs.st = data[:s_t]
    cs.e_t = data[:e_t]
    cs.save
   end 

   def self.get_all
    ClientSession.all.to_a
   end

   def self.sample_test(st, hourly=true)    
      puts "client sesison worker starts"
      col = hourly ? MonitoringDataCapped : MonitoringChild
      aggregate_data = col.collection.aggregate({"$match" => {"created_at" => {"$gte" => (st - 1.hour).utc, "$lt" =>  st.utc}}})
      aggregate_data.each do |val|
        c = val[:clients]
        c.each do |client|
          hsh = {}
          hsh[:mac] = client["MAC"]
          hsh[:access_point] = val["info"]["NASID"]
          hsh[:ip] = client["IPADDR"]
          hsh[:hostname] = client["HOSTNAME"]
          hsh[:device_type] = client["DEVICE_TYPE"]
          hsh[:s_t] = val["created_at"]
          hsh[:e_t] = val["created_at"]
          cs = ClientSession.where(:mac => client["MAC"],:e_t.gte => (st - 1.hour).utc, :e_t.lte => st.utc ).to_a.last
          if cs.present?
            ClientSession.update_data cs, hsh
          else
            ClientSession.save_data hsh
          end
        end
       end
    end 
end

