# == Schema Information
#
# Table name: ntp_servers
#
#  id                  :integer          not null, primary key
#  is_enabled          :boolean
#  urls                :text
#  location_network_id :integer
#  created_at          :datetime
#  updated_at          :datetime
#

class NtpServer < ActiveRecord::Base
  resourcify
  include RedisWrapper
  include PublicActivity::Model

  tracked owner: ->(controller, model) { controller && controller.tracked_current_user },params:
  { :attributes => proc {|controller, model_instance| { "ntp_configuration(#{model_instance.location_network.network_name})" => model_instance.changes}}},organisation_id: ->(controller, model) { controller && controller.tracked_current_user.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}
  
  belongs_to :location_network

  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

  def update_configuration(des = false)
    redis_set "ntp#{self.id}", {"ENABLE" => self.is_enabled? ? 1 : 0, "NTP_LIST" => self.urls.split(',')}.to_json
    redis_del "ntp#{self.id}" if des
    self.location_network.router_inventories.each {|ri| ri.update_redis }
  end

  def json_build
    {is_enabled: self.is_enabled, urls: self.urls}
  end
end
