module ApplicationHelper
  def format_date(date,type)
    case type
      when :short_no_year
        date.strftime("%b %d")
      when :short
        date.strftime("%d-%b-%Y")
      when :long
        date.strftime("%B %d, %Y")
      when :long_day_of_week
        date.strftime("%a %B %d, %Y")
      when :sort
        date.strftime("%Y-%m-%d")
      when :calendra
        date.strftime("%d/%m/%Y")
      when :date_time
        date.strftime("%b %d %Y, %H:%M:%S")
      when :readable
        date.strftime("%e %b %Y %H:%M:%S %z")
      when :default
        date.strftime("%b %d %Y")
    end
  end

  # def get_colors
  #   if @current_organisation.present? && @current_organisation.branding
  #     {footer: @current_organisation.footer_bg_color, header: @current_organisation.header_bg_color, sidebar: @current_organisation.sidebar_bg_color}
  #   else
  #     {footer: "#e0e0e0", header: "#222222", sidebar: "#e0e0e0"}
  #   end
  # end

  def get_org_name
    if @current_organisation.present? && @current_organisation.branding
      {short: @current_organisation.organisation_name, full: @current_organisation.organisation_name}
    else
      {short: "Wavespot", full: "Wavespot"}
    end 
  end

  def get_node_url
    default_domain = APPLICATION[Rails.env]["node_url"]
    if @current_organisation.present? && @current_organisation.branding && @current_organisation.live_domain.present?
      "//#{@current_organisation.live_domain}"
    else
      "#{default_domain}"
    end
  end

  def grouped_collection_of_values val
    # @ssid={}
    # hsh = {}
    # hsh.compare_by_identity
    # @ssid["Other"] = [['All Interfaces','all'],['All Ssids', 'ssids'], ['Wired', 'wired']]
    # @ssid
    AccessControlList::SERVICES[val]    
  end

  def sidebar_helper(arr)
    sidebar = ""
    arr.each do |k, v|
      next unless v.select {|i| i['visible'] == true }.present?
      sidebar << "<li class='has-sub'><a href='#'><i class='fa fa-#{k['icon']} text-info-name main-menu-name'></i><span>#{k['value']}</span></a><ul>"
      v.each do |sub_menu|
        next unless sub_menu["visible"]
        sidebar << "<li>"
        sidebar << link_to(sub_menu['value'], sub_menu['link'])
        sidebar << "</li>"
      end
      sidebar << "</ul></li>"
    end
    return sidebar.html_safe
  end

  # def grouped_collection_of_tags
  #   tags = {}
  #   tags["Network Tags"] = current_user.location_networks.map {|i| [i.tags.pluck(:name, :id)].flatten.uniq}.reject{|i| i.blank?}.map{|k| [k.first, "Tag:#{k.first}"]}.uniq
  #   tags["Location Network"] = current_user.networks_with_full_access.map {|ln| [ln.network_name, "network:#{ln.id}"]}
  #   tags
  # end

  def grouped_collection_of_tags
    tags = {}
    # tags["Network Tags"] = current_user.location_networks.map {|i| [i.tags.pluck(:name, :id)].flatten.uniq}.reject{|i| i.blank?}.map{|k| [k.first, "Tag:#{k.first}"]}.uniq
    arr = []
    current_user.location_networks.map {|i| [i.tags.pluck(:name, :id)].flatten.uniq}.reject{|i| i.blank?}.each {|i| if (i.length > 1);  i.each_slice(2){|a,b| arr << [a,b]} ;else; arr << i ;end;}
    tags["All Networks"] = [["All", "all:all"]]
    tags["Network Tags"] = arr.uniq.map{|k| [k.first, "Tag:#{k.first}"]} if arr.present?
    tags["Network"] = current_user.networks_with_full_access.map {|ln| [ln.network_name, "network:#{ln.id}"]}
    tags
  end  

  def nw_tags user
    hsh = {}
    user.organisation.location_networks.each{|i| hsh[i.id] = i.tags.pluck(:name).uniq}
    hsh
  end

  def selected_full_tags user
    check = user.network_tags.keys
    val = user.network_tags
    arr =[]
    if check.include?("full")
      tags, locations = val["full"].partition{|i| i.split(':').include?("Tag") }
      arr <<  tags
      arr << locations
      arr.flatten.uniq
    end
  end

  def selected_limited_tags user
    check = user.network_tags.keys
    val = user.network_tags
    arr =[]
    if check.include?("limited")
      tags, locations = val["limited"].partition{|i| i.split(':').include?("Tag") }
      arr <<  tags
      arr << locations
      arr.flatten.uniq
    end
  end  

  def network_access_values user, hah
    check = user.network_tags.keys
    val = user.network_tags
    per_tags =  hah.values.flatten.uniq
    hash = {}
    if check.include?("full")
      hsh = {}
      tags, locations = val["full"].partition{|i| i.split(':').include?("Tag") }
      tag_val = tags.map{|i| i.split(':').last}
      res = tag_val.select{|i| per_tags.include?(i)}
      hsh["tags"] = res
      hsh["all"] = true if locations.delete("all:all") if locations.present?
      hsh["locations"] = LocationNetwork.where(:id => locations.map{|i| i.split(':').last}).pluck(:network_name) if locations.present?
      hash["full"] = hsh
    end
    if check.include?("limited")
      hsh1 = {}
      l_tags, l_locations = val["limited"].partition{|i| i.split(':').include?("Tag") }
      tag_val = l_tags.map{|i| i.split(':').last}
      res = tag_val.select{|i| per_tags.include?(i)}
      hsh1["tags"] = res
      hsh1["all"] = true if l_locations.delete("all:all") if l_locations.present?
      hsh1["locations"] = LocationNetwork.where(:id => l_locations.map{|i| i.split(':').last}).pluck(:network_name) if l_locations.present?
      hash["limited"] = hsh1
    end    
    hash
  end


  def collection_of_config_mappings collection
    resource_mapping = ConfigMapping::RESOURCE_MAP
    resource_mapping["HWC"] = "HardwareCategory"
    hash = collection.group_by {|c| c.split(':')[0] }
    organisation = current_user.organisation
    hash.each do |k, v|
      case resource_mapping[k]
      when "LocationNetwork"
        hash[k] = ["ALL"]#LocationNetwork.where(id: v.map {|ln| ln.split(':')[1]}).pluck(:network_name)
      when "RouterInventory"
        hash[k] = organisation.router_inventories.where(id: v.map {|ap| ap.split(':')[1]}).pluck(:mac_id)
      when "ActsAsTaggableOn::Tag"
        hash[k] = organisation.router_inventories.tag_counts.where(id: v.map {|tag| tag.split(':')[1]}).pluck(:name)
      when "HardwareCategory"
        hash[k] = HardwareCategory.where(id: v.map {|hw| hw.split(':')[1]}).map {|d| LocationNetwork::HW_CATEGORY_MAP[d.name]}
      end
    end
  end

  def grouped_collection_of_ap_and_networks(config = '')
    hash = {}
    organisation = current_user.organisation
    lns = organisation.location_networks.map {|ln| [ln.network_name, "network:#{ln.id}"]}
    hash["Network"] = lns 
    ris = organisation.router_inventories.map {|ri| ["#{ri.name.present? ? (ri.name + " (#{ri.mac_id.last(8)})") : ri.mac_id}", "AP:#{ri.id}"]}
    hash["APs"] = ris
    if config == 'Radio'
      used_ln_ids = []
      used_rn_ids = []
      if !@radio_profile.new_record?
        radio_profiles = organisation.radio_profiles - [@radio_profile]
      else
        radio_profiles = organisation.radio_profiles
      end    
      radio_profiles.map do |radio|
        used_ln_ids += radio.location_networks.map {|ln| [ln.network_name, "network:#{ln.id}"]}
        used_rn_ids += radio.router_inventories.map {|ri| ["#{ri.name.present? ? (ri.name + " (#{ri.mac_id.last(8)})") : ri.mac_id}", "AP:#{ri.id}"]}
      end 
      hash["Network"] = (lns - used_ln_ids)
      hash["APs"] = (ris - used_rn_ids)
    end  
    hash
  end

  def grouped_collection_of_ap_and_networks_and_tags
    hash = {}
    tag = []
      hash["Network"] = current_user.networks_with_full_access.map {|ln| [ln.network_name, "network:#{ln.id}"]}
      hash["APs"] = current_user.router_inventories_full.map {|ri| ["#{ri.name.present? ? (ri.name + " (#{ri.mac_id.last(8)})") : ri.mac_id}", "AP:#{ri.id}"]}
      current_user.router_inventories_full.each {|ri| ri.tags.each{|l| tag << [l.name, "tag:#{l.id}"]}}
      hash["Tags"] = tag.uniq
    hash
  end

  def grouped_collection_of_venue_types
    hash = {}
    hash["Unspecified"] = ["Unspecified"]
    hash["Assembly"] = ["arena", "Passenger Terminal", "Amphitheater"]
    hash["Business"] = ["Doctor or Dentist office", "Fire Station", "Post Office"]
    hash["Educational"] = ["School, Primary", "University or College"]
    hash["Factory and Industrial"] = ["Unspecified Factory and Industrial", "Factory"]
    hash
  end

  def grouped_collection_of_authentication
    hash = {}
    hash["Non-EAP Inner Authentication"] = ["Reserved", "PAP", "CHAP", "MSCHAP", "MSCHAPV2"]
    hash["EAP Inner Authentication"] = ["EAP-TLS", "EAP-SIM", "EAP-AKA", "EAP-TTLS with MSCHAPv2"]
    hash["Credentials"] = ["SIM", "USIM", "NFC Secure Element", "Hardware Token"]
    hash["Tunneled EAP Method Credentials"] = ["SIM", "USIM", "NFC Secure Element", "Hardware Token"]
    hash
  end
  
   def grouped_collection_of_ap_and_networks_current_network(config = '')
    hash = {}
    lns = [["All", "network:#{@current_network.id}"]]
    hash["Network"] = lns 
    ris = @current_network.router_inventories.map {|ri| ["#{ri.name.present? ? (ri.name + " (#{ri.mac_id.last(8)})") : ri.mac_id}", "AP:#{ri.id}"]}
    hash["APs"] = ris
    if config == 'static'
      mac = []
      @routers = @current_network.router_inventories
      @routers.each do |ri|
        r = $redis.hgetall "AP:#{ri.mac_id}"
        version = r['version'].present? ? r["version"].split('.').join() : '0'
        if version >= "20223" || r["version"] == nil
          mac << ["#{ri.name.present? ? (ri.name + " (#{ri.mac_id.last(8)})") : ri.mac_id}","AP:#{ri.id}"]
        end  
      end
      hash["Network"] = lns
      hash["APs"] = mac
    end  
    hash
  end

  def grouped_collection_of_ap_and_networks_switch(hw_part)
    hash = {}
    lns = [["All", "network:#{@current_network.id}"]]
    hash["Network"] = lns 
    ris = hw_part.router_inventories.map {|ri| ["#{ri.name.present? ? (ri.name + " (#{ri.mac_id.last(8)})") : ri.mac_id}", "AP:#{ri.id}"]}
    hash["APs"] = ris  
    hash
  end

  def ssid_band band
    if band.to_s == "5" || band.to_s == "2"
      link_to "5 GHz", '#', :class => "label label-warning"
    elsif band.to_s == "1" || band.to_s == "2.4"
      link_to "2.4 GHz", '#', :class => "label label-success"
    elsif band.to_s == "both" || band.to_s == "3" 
      link_to "both", "#", :class => "label label-success"
    elsif band.to_s == "6" || band.to_s == "4" 
      link_to "6 Ghz", "#", :class => "label label-info"
    end
  end

  def router_channel_nummber router, network_radio
    if router.vendor_type == "4"
      rd = JSON.parse($redis.hget("AP:#{router.mac_id}", "RD") || '{}')

      return {"2.4" => ((rd['1']  || {})['CH'] || '-'), "5" => ((rd['2']  || {})['CH'] || '-'), "6" => ((rd['3']  || {})['CH'] || '-')}
    else
      # return {"2.4" => router.channel || 'Auto'} unless router.associated_radio_profile.present? || network_radio.present?
      
      radio_profile = nil
      if router.associated_radio_profile.present?
        radio_profile = router.associated_radio_profile
      else
        radio_profile = network_radio
      end
      unless radio_profile.present?
        radio_profile = get_default_radio_profile
      end
      radio_profile.radio_settings.inject({}) do |h,v|
        h[v.band] = (v.channel == 0 ? "Auto" : v.channel) unless v.is_disable
        h
      end
    end
  end

  def get_default_radio_profile
    default_radio = JSON.parse($redis.get "default_radio")
    radio_profile = RadioProfile.new(name: default_radio["NAME"], country_code: default_radio["COUNTRY_CODE"], "radio_settings_attributes" => [{band: default_radio["RADIO_SETTINGS"][0]["BAND"] == "2" ? "5" : "2.4", channel_utlilization: default_radio["RADIO_SETTINGS"][0]["CH_UTIL_EN"], is_disable: default_radio["RADIO_SETTINGS"][0]["DISABLE"], country_ie: default_radio["RADIO_SETTINGS"][0]["COUNTRY_IE"], channel: default_radio["RADIO_SETTINGS"][0]["CHANNEL"]}, {band: default_radio["RADIO_SETTINGS"][1]["BAND"] == "2" ? "5" : "2.4", is_disable: default_radio["RADIO_SETTINGS"][1]["DISABLE"], country_ie: default_radio["RADIO_SETTINGS"][1]["COUNTRY_IE"], channel: default_radio["RADIO_SETTINGS"][1]["CHANNEL"], power: default_radio["RADIO_SETTINGS"][1]["TXPOWER"], require_mode: default_radio["RADIO_SETTINGS"][1]["REQUIRE_MODE"], bandwidth: default_radio["RADIO_SETTINGS"][1]["CH_BW"]}])
    radio_profile
  end

  def router_power_nummber router, network_radio
    return {"2.4" => router.channel || 'Auto'} unless router.associated_radio_profile.present? || network_radio.present?
    radio_profile = nil
    if router.associated_radio_profile.present?
      radio_profile = router.associated_radio_profile
    else
      radio_profile = network_radio
    end

    radio_profile.radio_settings.inject({}) do |h,v|
      h[v.band] = (v.power == 0 ? "Auto" : v.power) unless v.is_disable
      h
    end
  end

  def ap_info_mac(ri)
   mac = []
   if ri.name.present?
     mac << link_to(ri.name, inventory_path(ri.mac_id), :class => "text-info mac_details",:data => {:mac => "#{ri.mac_id}"}, "data-container" => 'body', "data-html" => 'true' ,"data-placement" =>'right' ,'data-toggle' => 'popover','data-title' => "",'data-content'=> "<img src='/assets/dashboard_spinner.gif' alt='Spinner'>")
     mac << "<span style='padding-left:15p'>(&nbsp;#{ri.mac_id.split(':').last(3).join(':')} &nbsp;)</span>".html_safe
   else
     mac << link_to(ri.mac_id, inventory_path(ri.mac_id), :class => "text-info mac_details", :data => {:mac => "#{ri.mac_id}"}, "data-container" => 'body', "data-html" => 'true' ,"data-placement" =>'right' ,'data-toggle' => 'popover','data-title' => "",'data-content'=> "<img src='/assets/dashboard_spinner.gif' alt='Spinner'>")
   end
 end

  def ap_info(ri)
   mac = []
   if ri.name.present?
     mac << link_to(ri.name, inventory_path(ri.id), :class => "text-info mac_details",:data => {:mac => "#{ri.mac_id}"}, "data-container" => 'body', "data-html" => 'true' ,"data-placement" =>'right' ,'data-toggle' => 'popover','data-title' => "",'data-content'=> "<img src='/assets/dashboard_spinner.gif' alt='Spinner'>")
     mac << "<span style='padding-left:15p'>(&nbsp;#{ri.mac_id.split(':').last(3).join(':')} &nbsp;)</span>".html_safe
   else
     mac << link_to(ri.mac_id, inventory_path(ri.id), :class => "text-info mac_details", :data => {:mac => "#{ri.mac_id}"}, "data-container" => 'body', "data-html" => 'true' ,"data-placement" =>'right' ,'data-toggle' => 'popover','data-title' => "",'data-content'=> "<img src='/assets/dashboard_spinner.gif' alt='Spinner'>")
   end
 end

  def show_tags(list,controller)
    if list.resourceable_type == 'RouterInventory'
       path = inventory_path(list.resourceable.id)
       name = list.resourceable.mac_id
       title = 'AP'
    elsif list.resourceable_type == 'LocationNetwork'
       path = home_path(list.resourceable.id)
       name = list.resourceable.network_name
       title = 'network'
    elsif list.resourceable_type == 'ActsAsTaggableOn::Tag'
       path = {:controller=>controller,:action=>:showing_tag, :id=>list.resourceable.name, :type=>'tag'}
       name = list.resourceable.name
       title = 'tag'
    end
    return name,path,title
  end

  def type_name val
    RouterInventory::UPLINK_TYPE[val]
  end
end
