# == Schema Information
#
# Table name: vpn_configs
#
#  id                   :integer          not null, primary key
#  name                 :string(255)
#  ike_time             :string(255)
#  l_subnet             :string(255)
#  remote_ip            :string(255)
#  remote_nw_ip         :string(255)
#  remote_nw_subnet     :string(255)
#  pre_shared_key       :string(255)
#  ike                  :string(255)
#  esp                  :string(255)
#  is_enabled           :string(255)
#  location_network_id  :integer
#  created_at           :datetime
#  updated_at           :datetime
#  is_server            :boolean
#  enable_server_client :boolean
#

class VpnConfig < ActiveRecord::Base
  include AssociatedResource
  include PublicActivity::Model
  belongs_to :location_network
  
  serialize :server_peer, Array

  DIFFIE_HELLMAN = ['modp768', 'modp1024', 'modp1536', 'modp2048', 'modp3072', 'modp4096', 'modp6144', 'modp8192']
  IKE_ENCRYPTION =  ['3des', 'aes128', 'aes192', 'aes256']
  IKE_HASH = ['md5', 'md5_128', 'sha1', 'sha256', 'sha384', 'sha512']

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

  def update_redis
    unless self.blank?
      lns = self.location_networks
      routers =  RouterInventory.where(location_network_id: lns.pluck(:id)) + self.router_inventories
      (routers.uniq || []).each{|x| x.update_redis}
    end
  end

  after_save do |vpn|
    vpn.update_redis
  end

  after_destroy do |vpn|
    vpn.update_redis
  end

  def get_local_subnet_name
    l_sub_id = self.l_subnet
    if l_sub_id.present? && l_sub_id.match('L')
      l_sub_id.gsub!('L', '')
      l_sub_name = $redis.get "wc#{l_sub_id}"
      l_sub_name = l_sub_name.present? ? JSON.parse(l_sub_name)['NAME'] : WiredConfig.find_by_id(l_sub_id).try(:name)
    else
      l_sub_name = $redis.get "ns#{l_sub_id}"
      l_sub_name = l_sub_name.present? ? JSON.parse(l_sub_name)['SSID'] : NetworkSsid.find_by_id(l_sub_id).try(:ssid_name)
    end
    
    return l_sub_name
  end

  def get_local_subnet_name
    l_sub_id = self.l_subnet
    if l_sub_id.present? && l_sub_id.match('VL')
      l_sub_id.gsub!('VL', '')
      l_sub_name = VLan.where(id: l_sub_id).first.try(:v_lan_id)
    else
      l_sub_name = $redis.get "ns#{l_sub_id}"
      l_sub_name = l_sub_name.present? ? JSON.parse(l_sub_name)['SSID'] : NetworkSsid.find_by_id(l_sub_id).try(:ssid_name)
    end
    
    return l_sub_name
  end
end
