class RadiusConfigurationsController < ApplicationController
  include ChangeNetwork
  before_action :authenticate_user!
  before_action :dashboard_topbar

  before_action :set_article, only: [:updat, :delete]
  load_and_authorize_resource :class => RadiusConfiguration
  # check_policy_for :create, :update, :destroy, with: RadiusConfiguration, id_param: :id
  skip_load_resource :only => [:create, :change_network]


  def index
    @radius_configuration = params[:id].blank? ? RadiusConfiguration.new : RadiusConfiguration.where(id: params[:id]).first
    if !params[:id].blank? and @radius_configuration.try(:id).blank?
     flash[:notice] = 'Requested Radius configuration not found!'
     @radius_configuration = RadiusConfiguration.new
    end
    @existing_configs = current_user.organisation.radius_configurations rescue []
  end

  def create
    if current_user.organisation.radius_configurations.create(radius_configuration_params)
      flash[:success] = "Successfully created radius configuration"
    else
      flash[:error] = "Oops! there was some in problem creating radius configuration"
    end
    redirect_to :action=>:index
  end

  def updat
    if @radius_configuration.update(radius_configuration_params)
      flash[:success] = "Successfully updated radius configuration #{@radius_configuration.radius_name}"
    else
      flash[:error] = "Oops! there was some in problem updating radius configuration"
      Rails.logger.warn "#{@radius_configuration.errors.full_messages}"
    end
    redirect_to :action=>:index
  end

  def delete
    if @radius_configuration.destroy
      flash[:success] = "Successfully deleted radius configuration #{@radius_configuration.radius_name}"
    else
      flash[:error] = "Oops! there was some problem in deleting radius configuration"
      Rails.logger.warn "#{@radius_configuration.errors.full_messages}"
    end
    redirect_to :action=>:index
  end

  def change_network
    change_user_network
  end

  private

  def radius_configuration_params
    params.require(:radius_configuration).permit(:radius_name,:radius_ip,:radius_port,:radius_secret,:type)
  end

  def set_article
    @radius_configuration = RadiusConfiguration.where(:id => params[:id]).first
    if @radius_configuration.blank?
      flash[:notice] = "Requested Radius Configuration not found"
      redirect_to :action=>:index
    end
  end
end
