class RadioProfilesController < ApplicationController
  include ChangeNetwork
  before_filter :authenticate_user!
  before_filter :check_network_presence?, only: [:index, :show, :create, :update, :destroy], if: Proc.new { |c| c.request.format.json? }
  before_filter :dashboard_topbar, if: Proc.new { |c| !c.request.format.json? }
  before_filter :set_radio_profile, :only => [:edit, :update, :destroy]
  load_and_authorize_resource :class => RadioProfile,:except => [:change_network]
  check_policy_for :create, :update, :destroy, with: RadioProfile, id_param: :id
  skip_load_resource :only => [:new, :create]

  def index
    unless @current_network.blank?
      @default_radio = $redis.get("default_radio_#{current_user.organisation_id}") || $redis.get("default_radio")
      @default_radio = JSON.parse(@default_radio) if @default_radio.present?
      @exisitng_radio_profiles = @current_network.radio_profiles
      if request.format.json?
        render json: {data: {radio_profiles: @exisitng_radio_profiles.map(&:json_build)}} 
      end
    end
  end

  def show
    render json: {data: {radio_profile: @radio_profile.json_build}}
  end

  def new
    unless @current_network.blank?
      @radio_profile = @current_network.radio_profiles.build
      @radio_settings = [@radio_profile.radio_settings.build(band: "2.4"),@radio_profile.radio_settings.build(band: "5"),@radio_profile.radio_settings.build(band: "6")]
      @aps_collection = RadioProfile.grouped_collection_of_ap_and_network @current_network
    end
  end

  def create
    if params[:clone] == "true"
      json_data = $redis.get("default_radio_#{current_user.organisation_id}") || $redis.get("default_radio")
        
      unless json_data
        flash[:error] = "Default radio profile not found for cloning."
        return redirect_to radio_profiles_path
      end
      default_radio = JSON.parse(json_data)
      radio_settings = {}
      default_radio['RADIO_SETTINGS'].each do |setting| 
        radio_settings["#{default_radio['RADIO_SETTINGS'].index(setting)}"] = {"band" =>  setting['BAND'].to_i == 1 ? "2.4" : setting['BAND'].to_i == 2 ? "5" : "6", "channel" => setting['CHANNEL'] == "0" ? "Auto" : setting['CHANNEL'],  "power" => setting['TXPOWER']== "0" ? "Auto" : setting['TXPOWER'], "is_disable" => setting['DISABLE'] == 0 ? false : true, "channel_utlilization" => setting['CH_UTIL_EN'] == 0 ? "false" : "true", "country_ie" => setting['COUNTRY_IE'] == 0 ? "false" : "true", "bandwidth" => setting['CH_BW'], "maximum_clients"=>"", "multiple_bssid" => "false", "beacon_rate" => "None", "beacon_interval" => "", "dtim_period" => "",  "multicast" => "None", "bss_color"=>"0", "valid_auto_channel"=>[""]}
      end
      radio_management = {"client_steering"=>"true", "assoc_steering"=>"false", "required_probe_snr"=>"", "required_roam_snr"=>"", "load_kick_threshold"=>"", "auto_channel_balancing"=>"false"}
      transformed_data = {
        "name" => "#{default_radio["NAME"]} Clone",
        "country_code" => 'US',
        "radio_settings_attributes" => radio_settings,
        "radio_management_attributes" => radio_management
      }

      @radio_profile = @current_network.radio_profiles.build(transformed_data)
    else
      @radio_profile = @current_network.radio_profiles.build(radio_profile_params)
    end
    if @radio_profile.save
      flash[:success] = "Radio profile #{@radio_profile.name} was created Successfully"
      json_data = {data: @radio_profile.json_build , status: 200}
    else
      json_data = {message: "Radio Profile is not created. Please check again.", status: 422}
      flash[:error] = "Oops! Problem in creating radio profile"
      Rails.logger.warn "#{@radio_profile.errors.full_messages}"
      @exisitng_radio_profiles = @current_network.radio_profiles.all
    end
    if request.format.json?
      render json: json_data, status: json_data[:status]
    else
      redirect_to radio_profiles_path
    end
  end

  def edit
    @radio_settings = @radio_profile.radio_settings unless @radio_profile.blank?
    @radio_management = @radio_profile.radio_management unless @radio_profile.blank?
    @aps_collection = RadioProfile.grouped_collection_of_ap_and_network @current_network, @radio_profile
  end

  def update
    if @radio_profile.update_attributes(radio_profile_params)
      flash[:success] = "Radio profile #{@radio_profile.name} was updated Successfully"
      json_data = {data: @radio_profile.json_build , status: 200}
    else
      flash[:error] = "Oops! Problem in updating radio profile"
      json_data = {message: "Radio profile is not updated (Reason: #{@radio_profile.errors.full_messages}).", status: 422}
      Rails.logger.warn "#{@radio_profile.errors.full_messages}"
      @exisitng_radio_profiles = @current_network.radio_profiles.all
    end
    if request.format.json?
      render json: json_data, status: json_data[:status]
    else
      redirect_to radio_profiles_path
    end
  end

  def destroy
    if @radio_profile.destroy
      flash[:success] = "Radio profile #{@radio_profile.name} was deleted Successfully"
      json_data = {data: {}, status: 200}
    else
      flash[:error] = "Oops! Problem in deleting radio profile #{@radio_profile.name}"
      Rails.logger.warn "#{@radio_profile.errors.full_messages}"
      json_data = {message: "Radio profile is not deleted. Please try again." , status: 422}
    end    
    if request.format.json?
      render json: json_data, status: json_data[:status]
    else
      redirect_to radio_profiles_path and return
    end
  end

  def change_network
    change_user_network
  end

  protected

    def current_ability
      if Rails.cache.exist?("views/new_sidebar_menu/role_#{current_user.role.id}_#{current_user.is_super_admin}") || Rails.cache.exist?("views/noc_sidebar_menu/role_#{current_user.role.id}_#{current_user.is_super_admin}")
        @current_ability ||= Ability::RadioProfileAbility.new(current_user)
      else
        @current_ability ||= Ability.new(current_user)
      end
    end
    
    def set_radio_profile
      @radio_profile = @current_network.radio_profiles.where(id: params[:id]).first
      if @radio_profile.blank?
        flash[:notice] = "Requested Radio profile not found!"
        redirect_to radio_profiles_path
      end
    end

    def radio_profile_params
      params.require(:radio_profile).permit(:name, :country_code,:location_network_id, associated_resources: [], radio_settings_attributes: [:band, :channel, :power, :_destroy, :id, :is_disable, :channel_utlilization, :country_ie, :require_mode,:bandwidth, :maximum_clients, :multiple_bssid, :beacon_rate, :beacon_interval, :dtim_period, :multicast, :ema, :bss_color, :valid_auto_channel => []], radio_management_attributes: [:client_steering, :assoc_steering, :steering_auto_channel, :required_probe_snr, :required_roam_snr, :load_kick_threshold, :auto_channel_balancing, :_destroy, :id])
    end
end
