class ClientsController < ApplicationController
  include ChangeNetwork
  before_action :authenticate_user!
  before_action :dashboard_topbar
  before_action :set_org_id
  skip_load_resource :only => [:change_network]

  # def client_show
  #   unless params[:nas_id].blank?
  #     @rv = RouterInventory.where(mac_id: params[:nas_id]).last
  #     @last_monitored_record = Monitoring.get_client_last_details(params[:nas_id],params[:mac_id])
  #   else
  #     @last_aggregated_data = ClientAggregateData.find_recent params[:mac_id], @current_network.id
  #     @last_monitored_record = Monitoring.get_client_last_details(@last_aggregated_data.ap, params[:mac_id])
  #     @rv = RouterInventory.where(mac_id: @last_aggregated_data.ap).last
  #   end
  # end

  def client_show
    @client_device = ClientDevice.where(mac: params[:mac_id]).last
    @last_monitored_record = Monitoring.get_client_last_details(params[:nas_id],params[:mac_id], @current_network.id)
    @client_details = (client_details.present? ? client_details : {})
    @rv = RouterInventory.where(mac_id: @last_monitored_record["access_point"]).last #if @last_aggregated_data.present?
  end

  def client_details
    values = ClientDevice.get_all @org_id 
    hsh = {}
    values.each {|i| hsh[i[:mac]] = {:name => (i[:nick_name] || i[:original_name].to_s) , :original_name=> i[:original_name], :mac => i[:mac]}}
    hsh
  end  

  def monitoring_Details
    ClientDevice.monitoring_details @org_id 
  end


  def clients_upload_download
    @monitoring_clients = (monitoring_Details.present? ? monitoring_Details : [])
    @client_details = (client_details.present? ? client_details.to_json : "{}")
    get_clients
  end

  def get_clients
    unless @current_network.blank?
      @vlan = @current_network.v_lans.present? ? Hash[@current_network.v_lans.map {|s| ["VL#{s.id}", s.v_lan_id]}].to_json : "{}"
      @nas_ids = @current_network.router_inventories.pluck(:mac_id)
      @n = {}
      @current_network.router_inventories.pluck(:mac_id,:name).each{|a| @n["#{a[0]}"] = "#{a[1]}"}
      #@results = Monitoring.get_clients_upload_download(@nas_ids)
    end
  end

  def change_network
    change_user_network
  end

  private
    def set_org_id
      @org_id = current_user.organisation.id
    end  
end
