# == Schema Information
#
# Table name: loggings
#
#  id                  :integer          not null, primary key
#  name                :string(255)
#  logging_type        :string(255)
#  is_enabled          :string(255)
#  upload_type         :string(255)
#  location_network_id :integer
#  extra_data          :string(255)
#  created_at          :datetime
#  updated_at          :datetime
#

class Logging < ActiveRecord::Base

  include AssociatedResource
  include RedisWrapper
  include PublicActivity::Model
  belongs_to :location_network

  serialize :extra_data, Hash
  LOGGING_TYPE = {'calea' => 'CALEA','event_logging' => 'Event Logging', 'sys_log' => 'Syslog'}
  UPLOAD_TYPE = {'1' => 'FTP','2' => 'Local File System' }

  tracked owner: ->(controller, model) { controller && controller.tracked_current_user },params:
  { :attributes => proc {|controller, model_instance| { "logging(#{model_instance.name})" => model_instance.changes}}},organisation_id: ->(controller, model) { controller && controller.tracked_current_user.try(:organisation_id) },:location_network_id => proc {|controller, model_instance| model_instance.location_network_id}

  tracked assumed_by: proc {|controller, model| controller.user_assumed_by if controller}

 def update_redis
    unless self.blank?
      lns = self.location_networks
      routers = ''
      unless self.logging_type == 'event_logging'
        tags = self.tags.map(&:name)
        routers =  RouterInventory.where(location_network_id: self.location_network.id) + RouterInventory.tagged_with(tags)  + self.router_inventories
        (routers.uniq || []).each{|x| x.update_redis}
      else
        routers =  RouterInventory.where(location_network_id: self.location_network.id)
        (routers.uniq || []).each do |x|
          $redis.hset "AP:#{x.mac_id}", "EVENT_LOG",  self.is_enabled.to_s
          x.update_redis
         end
      end
    end
  end

  after_save do |x|
    x.update_redis
  end

  after_destroy do |x|
    x.update_redis
  end
end
