# == Schema Information
#
# Table name: organisations
#
#  id                :integer          not null, primary key
#  organisation_name :string(255)
#  created_at        :datetime
#  updated_at        :datetime
#  no_of_aps         :integer          default(200)
#  sms_config        :text
#

class Organisation < ActiveRecord::Base
  include PublicActivity::Model

  MODEL_NAME_MAP = {"RouterInventory" => "Device", "LocationNetwork" => "Network", "NetworkSsid" => "Network SSID", "VLan" => "VLAN"}

  tracked owner: ->(controller, model) { controller && controller.tracked_current_user if controller},params:
  { :attributes => proc {|controller, model_instance| { "organisation(#{model_instance.organisation_name})" => model_instance.changes}}},organisation_id: ->(controller, model) { controller && controller.tracked_current_user.organisation_id if controller && controller.tracked_current_user}

  tracked assumed_by: proc {|controller, model| controller.user_assumed_by if controller}
  
  serialize :organisation_settings, Hash
  serialize :sms_config, Hash
  has_many :users
  # serialize :sms_config, Hash
  validate :check_domain_and_live_domain
  has_attached_file :organisation_logo, size: { in: 0..5.megabytes }, styles: { site: "350x250", map: "250x250", thumb: "141x91!" }
  validates_attachment_content_type :organisation_logo, content_type: /\Aimage\/.*\z/, :message => "Oops!, organisation logo is invalid, Please Choose the correct format"
  validates_attachment_file_name :organisation_logo, matches: [/png\z/, /jpe?g\z/, /jpg\z/, /gif\z/]
  has_many :users, :dependent => :destroy
  accepts_nested_attributes_for :users,                                 
                                #:reject_if => lambda { |attrs| attrs.all? { |key, value| value.blank? } },
                                :allow_destroy => true
  do_not_validate_attachment_file_type :organisation_logo
  has_many :location_networks, dependent: :destroy
  has_many :router_inventories, dependent: :destroy

  has_many :radius_configurations
  has_many :radiuses, class_name: "Radius"
  has_many :radius_accountings
  has_many :radio_profiles, dependent: :destroy
  has_many :init_templates, dependent: :destroy
  has_many :reports, dependent: :destroy 
  has_many :ntp_servers, dependent: :destroy
  has_many :firewall_configs, dependent: :destroy
  has_many :loggings, dependent: :destroy
  has_many :vpn_configs, dependent: :destroy
  has_many :acl_groups
  has_many :switch_configurations, dependent: :destroy
  has_many :static_routes, dependent: :destroy
  has_many :portforwarding_groups
  has_many :snmp_configs
  has_many :sqms
  has_many :v_lans, dependent: :destroy
  has_many :network_ssids, dependent: :destroy
  has_many :wired_configs, dependent: :destroy
  has_many :upgrades
  has_many :upgrade_datas
  has_many :commands
  has_many :alerts, dependent: :destroy
  has_one :air_quality_config
  has_many :notification_groups,dependent: :destroy
  has_many :gateway_configs, dependent: :destroy
  has_many :sim_managements, dependent: :destroy
  has_many :purchase_orders, dependent: :destroy
  has_many :payment_invoices, dependent: :destroy
  has_many :sim_payment, dependent: :destroy
  has_one :roaming, dependent: :destroy
  has_many :integration_types, dependent: :destroy
  has_many :approved_firmwares

  has_one :sms_config, -> { where is_enabled: true, gateway_type: '1' }, class_name: "GatewayConfig"
  has_one :email_config, -> { where is_enabled: true, gateway_type: '2' }, class_name: "GatewayConfig"
  
  def check_domain_and_live_domain
    if self.organisation_domain.present? && self.live_domain.present?
      errors.add(:live_domain, "can't be the same as domain") if self.organisation_domain == self.live_domain
    end
  end

  def self.clear_sidekiq_queues
    count = Sidekiq::Queue.new('monitoring').count
    Sidekiq::Queue.new('monitoring').clear if count > 10000
    Sidekiq::Queue.new('alerts').clear if Sidekiq::Queue.new('alerts').count > 100
    ln_id = LocationNetwork.where(organisation_id: 190).joins(:router_inventories).group("location_network_id").count.select{|x,y| y < 2}
    $redis.hset("LN:DOWN:ALERT:ATTACHEDNETWORK", "1077", ln_id.keys.to_json)
  end

  def self.get_all_uplink_imei_in_csv
    header = ["Device MAC", "IMEI", "Organisation", "Status", "last_hb", "Date reported"]
    filename = "IMEI_CSV_LIST.csv"
    filename_new = "IMEI_CSV_LIST_#{Time.now.to_i}.csv"
    uplinks = Uplink.includes(router_inventory: [:location_network, :organisation]).where(uplink_type: "4")
    if File.exist?(filename)
      new_imei_arr = []
      arr_exisitng_imei = []
      CSV.read(filename).each do |csv|
        arr_exisitng_imei << csv[1]
      end
      CSV.open(filename,"a") do |csv|
        uplinks.each do |uplink|
          imei = (((uplink.last_mobile_status || "").split('|').select {|d| d.match(/IMEI/)}.first || "").split(':').last||"").strip.split(' ')
          unless imei.blank?
            next if arr_exisitng_imei.present? && arr_exisitng_imei.include?(imei.first)
            row = CSV::Row.new(header,[uplink.router_inventory.mac_id, imei.first, uplink.router_inventory.organisation.organisation_name, uplink.router_inventory.is_up? ? "ONLINE" : "OFFLINE", Time.at($redis.hget("AP:#{uplink.router_inventory.mac_id}", "last_hb").to_i), Date.today.to_s])
            csv << row
            new_imei_arr << row
          end
        end
      end
      CSV.open(filename_new, 'w', :headers => true) do |csv|
        csv << header
        new_imei_arr.each do |new_imei_row|
          csv << new_imei_row
        end
      end
    else
      CSV.open(filename, 'w', :headers => true) do |csv|
        csv << header
        uplinks.each do |uplink|
          imei = (((uplink.last_mobile_status || "").split('|').select {|d| d.match(/IMEI/)}.first || "").split(':').last||"").strip.split(' ')
          csv << [uplink.router_inventory.mac_id, imei.first, uplink.router_inventory.organisation.organisation_name, uplink.router_inventory.is_up? ? "ONLINE" : "OFFLINE", Time.at($redis.hget("AP:#{uplink.router_inventory.mac_id}", "last_hb").to_i), Date.today.to_s] unless imei.blank?
        end
      end
    end
    UserMailer.send_imei_list(filename_new).deliver  
  end

end
