# == Schema Information
#
# Table name: v_lans
#
#  id                   :integer          not null, primary key
#  organisation_id      :integer
#  network_ssid_id      :integer
#  v_lan_id             :string(255)
#  ip_type              :string(255)
#  ip_address           :string(255)
#  net_mask             :string(255)
#  dhcp_start_range     :string(255)
#  dhcp_end_range       :string(255)
#  dns1                 :string(255)
#  dns2                 :string(255)
#  gateway              :string(255)
#  created_at           :datetime
#  updated_at           :datetime
#  enable_gre_on_v_lan  :string(255)
#  enable_dhcp_on_v_lan :string(255)
#  name                 :string(255)
#

class VLan < ActiveRecord::Base
  resourcify
  #include RedisWrapper
  include PublicActivity::Model

  tracked owner: ->(controller, model) { controller && controller.tracked_current_user },params: { :attributes => proc {|controller, model_instance| {"v_lan(#{model_instance.v_lan_id})" => 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? ? model_instance.location_network_id : model_instance.network_ssid.location_network_id }
  
  tracked assumed_by: proc {|controller, model| controller.user_assumed_by if controller}

  belongs_to :organisation
  has_many :network_ssids, foreign_key: "vlan_id"
  has_and_belongs_to_many :wired_configs, join_table: :wired_configs_v_lans
  belongs_to :network_ssid
  belongs_to :location_network
  belongs_to :radius_authentication, foreign_key: "auth_radius_id"
  belongs_to :radius_accounting, foreign_key: "acc_radius_id"

  serialize :dhcp_mappings, Array
  serialize :dhcp_ranges, Array
  serialize :dhcp_options, Array

  DHCP_SERVER = {"1" => "Disabled", "2" => "Enabled", "3" => "Relay"}
  FORM_CONST = {"0" => "Disabled", "1" => "Enabled"}
  def update_redis
    set_redis
    if self.network_ssid.present?
      routers = RouterInventory.joins(location_network: :network_ssids).where("network_ssids.vlan_id = #{self.id}")
      (routers || []).each { |y| y.update_redis }
    else
      #routers = self.wired_configs.map {|w| w.applied_router_inventories}.flatten.compact.uniq
      self.wired_configs.uniq.each {|w| w.update_redis}
    end
    #(routers || []).each { |y|	y.update_redis }
  end

  after_create do |x|
    x.update_redis
  end

  after_update do |x|
    x.update_redis
  end

  after_destroy do |x|
    $redis.del "vl#{self.id}"
  end

  before_save do |vlan|
    if vlan.dhcp_relay_server == "1"
      vlan.dhcp_ranges = nil
      vlan.dhcp_lease_time = nil
      vlan.dhcp_mappings = nil
    else
    end  
  end
  
  def set_redis
    #{ "PORTAL_ENABLE" => (self.captive_portal).to_i, "MAC_AUTH" => self.mac_auth, "PORTAL_REDIR_URL" => self.splash_url,"SUCC_URL" => self.success_url,"WL_ENABLE" => (self.wallgarden).to_i,"WL_CONFIG" => (self.walled_garden_range.blank? ? [] : self.walled_garden_range.split(",")),"QOS" => {"BW_ENABLE" => self.per_user_qos.to_i == 0 ? 0 : 1,"BW"=> "#{self.per_user_qos.to_i}"},"DEF_INT_UPDATE_INTV" => self.default_interim_time,"DEF_IDLE_TO" => self.default_idle_timeout}
    if self.captive_portal.eql?"2"
      wavespot_portal =  APPLICATION['defaults']['CAPTIVE_PORTAL']
      wavespot_security =  APPLICATION['defaults']['SECURITY']
      captive_portal =  {"PORTAL_ENABLE" => wavespot_portal["PORTAL_ENABLE"],
          "PORTAL_REDIR_URL" => wavespot_portal["PORTAL_REDIR_URL"],
          "MAC_AUTH" => self.mac_auth,
          "WL_ENABLE" => wavespot_portal["WL_ENABLE"],
          "WL_CONFIG" => wavespot_portal["WL_CONFIG"],
          "ORIG_URL" => wavespot_portal["ORIG_URL"],
          "QOS" => {"BW_ENABLE" => wavespot_portal["QOS"]["BW_ENABLE"], "BW"=> wavespot_portal["QOS"]["BW"]}}
        radius = {"AUTH_SERVER" => wavespot_security["AUTH_SERVER"],"AUTH_PORT" => wavespot_security["AUTH_PORT"], "AUTH_SECRET" => wavespot_security["AUTH_SECRET"], "ACCT_SERVER" => wavespot_security["ACCT_SERVER"], "ACCT_PORT" => wavespot_security["ACCT_PORT"],"ACCT_SECRET" => wavespot_security["ACCT_SECRET"]}
    else
       captive_portal =  { "PORTAL_ENABLE" => self.captive_portal != '0' ? 1 : 0,
          "PORTAL_REDIR_URL" => self.splash_url,
          "WL_ENABLE" => (self.wallgarden).to_i,
          "WL_CONFIG" => (self.walled_garden_range.blank? ? [] : self.walled_garden_range.split(",")),
          "ORIG_URL" => self.overwrite_success_url == "false" ? "1" : "0",
          "SUCC_URL" => self.success_url,
          "QOS" => {"BW_ENABLE" => self.per_user_qos.to_i == 0 ? 0 : 1, "BW"=> "#{self.per_user_qos.to_i}"},
          "DEF_INT_UPDATE_INTV" => self.default_interim_time,
          "DEF_IDLE_TO" => self.default_idle_timeout,
          "PORTAL_AUTH_MODE" => "1" #Default should be '1' for CP with radius
          }
      captive_portal['MAC_AUTH'] = self.mac_auth if self.captive_portal == "1"
      #NOTE: PORTAL_AUTH_MODE - '1'=Radius, '2'=Local Auth
      captive_portal['PORTAL_AUTH_MODE'] = '2' if self.captive_portal == "3" #CP with local auth
      radius_auth_server = RadiusConfiguration.find_by_id(self.auth_radius_id)
      radius = {}
      unless radius_auth_server.blank?
        radius["AUTH_SERVER"] = radius_auth_server.radius_ip
        radius["AUTH_PORT"] = radius_auth_server.radius_port
        radius["AUTH_SECRET"] = radius_auth_server.radius_secret
      end
      radius_auth_server = RadiusConfiguration.find_by_id(self.acc_radius_id)
      unless radius_auth_server.blank?
        radius["ACCT_SERVER"] = radius_auth_server.radius_ip
        radius["ACCT_PORT"] = radius_auth_server.radius_port
        radius["ACCT_SECRET"] = radius_auth_server.radius_secret
      end
    end


    $redis.set "vl#{self.id}", {"VLAN_UNIQUE_ID" => self.uniq_identifier ,"VLANID"=> self.v_lan_id.try(:to_s), "GRE"=>self.enable_gre_on_v_lan.to_i,"IPADDR"=> self.ip_address,"NETMASK"=> self.net_mask,"DNS" => {"MODE" => self.dns_mode, "PRI_DNS" => self.dns1.to_s, "SEC_DNS" => self.dns2.to_s},"DHCP" => {"DHCP_ENABLE" => self.dhcp_relay_server,"LEASE_TIME" => self.dhcp_lease_time,"MAPPINGS" => self.dhcp_mappings,"RANGES" => self.dhcp_ranges,"OP" => self.dhcp_options},"NAT" => self.nat.to_i,"AS" => (self.active_scan ? 1 : 0),"WNA" => self.wna.to_i,"SECURITY" => radius,"CAPTIVE_PORTAL" => captive_portal, "UPLINK_PRIO" => self.uplink_priority,"QOS" => {"BW_ENABLE" => self.enable_vlan_qos? ? 1 : 0, "BW"=> "#{self.vlan_qos.to_i}"} }.to_json
   #{"VLAN_UNIQUE_ID" => self.uniq_identifier ,"VLANID"=> self.v_lan_id, "GRE"=>self.enable_gre_on_v_lan.to_i,"IPADDR"=> self.ip_address,"NETMASK"=> self.net_mask,"DNS" => {"MODE" => self.dns_mode, "PRI_DNS" => self.dns1.to_s, "SEC_DNS" => self.dns2.to_s},"DHCP" => {"DHCP_ENABLE" => self.dhcp_relay_server,"LEASE_TIME" => self.dhcp_lease_time,"MAPPINGS" => self.dhcp_mappings,"RANGES" => self.dhcp_ranges},"NAT" => self.nat.to_i,"AS" => (self.active_scan ? 1 : 0),"WNA" => self.wna.to_i,"SECURITY" => radius,"CAPTIVE_PORTAL" => { "PORTAL_ENABLE" => (self.captive_portal).to_i,"PORTAL_REDIR_URL" => self.splash_url,"WL_ENABLE" => (self.wallgarden).to_i,"WL_CONFIG" => (self.walled_garden_range.blank? ? [] : self.walled_garden_range.split(",")),"QOS" => {"BW_ENABLE" => self.per_user_qos.to_i == 0 ? 0 : 1,"BW"=> "#{self.per_user_qos.to_i}"},"DEF_INT_UPDATE_INTV" => self.default_interim_time,"DEF_IDLE_TO" => self.default_idle_timeout},}.to_json
  end

  def get_wired_configs
    self.location_network.wired_configs.select {|w| (w.port_configs || []).select {|e| e['PVID'] == self.v_lan_id || (e['VID'] || []).include?(self.v_lan_id)}.present?}
  end

  def uniq_identifier
    return 'VL' + self.id.to_s
  end


  def json_build
    {id: self.id, v_lan_id: self.v_lan_id, ip_address: self.ip_address, net_mask: self.net_mask, dhcp_start_range: self.dhcp_start_range, dhcp_end_range: self.dhcp_end_range, dns1: self.dns1, dns2: self.dns2, gateway: self.gateway, enable_gre_on_v_lan: self.enable_gre_on_v_lan, enable_dhcp_on_v_lan: self.enable_dhcp_on_v_lan, dns_mode: self.dns_mode, dhcp_relay_server: self.dhcp_relay_server, dhcp_mappings: self.dhcp_mappings, dhcp_ranges: self.dhcp_ranges, dhcp_lease_time: self.dhcp_lease_time, nat: self.nat, wna: self.wna, captive_portal: self.captive_portal, splash_url: self.splash_url, wallgarden: self.wallgarden, walled_garden_range: self.walled_garden_range, overwrite_success_url: self.overwrite_success_url, success_url: self.success_url, auth_radius_id: self.auth_radius_id, acc_radius_id: self.acc_radius_id, acc_radius_enabled: self.acc_radius_enabled, per_user_qos: self.per_user_qos, default_interim_time: self.default_interim_time, default_idle_timeout: self.default_idle_timeout, active_scan: self.active_scan, mac_auth: self.mac_auth, uplink_priority: self.uplink_priority, dhcp_options: self.dhcp_options, uam_secret_key: self.uam_secret_key, uam_secret: self.uam_secret}
  end
end
