class SqmsController < ApplicationController
  include ChangeNetwork
  before_action :authenticate_user!
  before_action :dashboard_topbar
  before_action :set_sqm, only: [:update, :destroy]
  load_and_authorize_resource :class => Sqm
  skip_load_resource :only => [:new, :create, :change_network]

  
  def index 
    @sqm = params[:id].blank? ? Sqm.new : current_user.organisation.sqms.find(params[:id])
    @sqms = current_user.organisation.sqms rescue []
    @ar = Sqm.tagging_lists(@sqm.tagging_lists)  unless params[:id].blank?
  end

  def new 
  end

  def edit
  end

  def create
    sqms = current_user.organisation.sqms.create(sqm_params)
    unless sqms.blank?
      flash[:success] = "Successfully created SQM"
    else
      flash[:error] = "Oops! there was some problem in creating SQM"
      Rails.logger.warn "#{sqms.errors.full_messages}"
    end
    redirect_to :action=>:index
  end

  def showing_tag
    case params[:type]
    when "network";@network=LocationNetwork.where(id: params[:id].to_i)
    when "tag"; @ris = RouterInventory.get_all_based_on_tag(params[:id])
    else; @ris = RouterInventory.where(id: params[:id].to_i)
    end
  end

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

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

  def change_network
    change_user_network
  end

  private

  def set_sqm
    @sqm = current_user.organisation.sqms.where(:id => params[:id]).first
      if @sqm.blank?
        flash[:notice] = "Requested SNMP configuration not found!"
        redirect_to :action=>:index
      end
  end

  def sqm_params
    params.require(:sqm).permit(:organisation_id,:is_enabled, :uplink, :upload_speed, :download_speed, :queuing_disciplines, :tagging_lists, :queue_setup_script, associated_resources: [])
  end
end