class SwitchConfigurationsController < ApplicationController
  before_action :authenticate_user!
  before_action :check_network_presence?, only: [:index, :show, :create, :update, :destroy], if: Proc.new { |c| c.request.format.json? }
  before_action :dashboard_topbar, unless: Proc.new { |c| c.request.format.json? }
  before_action :find_switch_configuration, :only => [:show, :update, :destroy]
  check_policy_for :create, :update, :destroy, with: SwitchConfiguration, id_param: :id

  skip_load_resource :only => [:change_network]

  # GET /switch_configurations
  # GET /switch_configurations.json
  def index
    @switch_configurations = []
    if params[:filter].present? 
      if params[:filter][:device_mac].present?
        @switch_configurations = @current_network.router_inventories.where(mac_id: params[:filter][:mac_id]).map {|d| d.get_associated_switch_configuration}
      elsif params[:filter][:device_model].present?
        hw_part = HardwarePart.where(name: params[:filter][:device_model]).last
        @switch_configurations = @current_network.switch_configurations.where(hardware_part_id: hw_part.try(:id)) unless hw_part.blank?
      end
    else 
      @switch_configurations = @current_network.switch_configurations rescue []
    end

    if request.format.json?
      render json: {data: {switch_configurations: @switch_configurations.map(&:json_build)}}
    end
  end

  # GET /switch_configurations/1
  # GET /switch_configurations/1.json
  def show
    switch_conf = @current_network.switch_configurations.where(id: params["id"]).last
    if request.format.json? && switch_conf.present?
      render json: {data: {switch_configuration: switch_conf.json_build}}
    else
      render json: {message: "Requested Switch configuration is not belongs to this network"}, status: 422
    end
  end

  def new
    @switch_configuration = @current_network.switch_configurations.new
    @switch_hardware_parts = HardwarePart.switch_hardware_parts
    @selected_hw_part =  @switch_hardware_parts.first 
    @switch_port_configurations = [@switch_configuration.switch_port_configurations.build]
    @aps_collection = SwitchConfiguration.grouped_collection_of_aps(@current_network, @selected_hw_part.try(:id))
    @port_configurations = @switch_configuration.switch_port_configurations.map {|d| [d.port_number, d]}
    @port_configuration = @switch_configuration.switch_port_configurations.build
  end

  # POST /switch_configurations
  # POST /switch_configurations.json
  def create
    @switch_configuration = @current_network.switch_configurations.new(switch_configuration_params)
    @switch_configuration.organisation_id = @current_network.organisation_id
    if @switch_configuration.save
      flash[:success] = "Switch Configuration Successfully created."
      json_data = {data: @switch_configuration.json_build , status: 200}
    else
      flash[:error] = "Oops! there was some problem in creating Switch Configuration"
      Rails.logger.warn "#{@switch_configuration.errors.full_messages}"
      json_data = {message: "Switch Configuration is not created. Please try again." , status: 422}
    end
    if request.format.json?
      render json: json_data, status: json_data[:status]
    else
      redirect_to edit_switch_configuration_path(@switch_configuration)
    end
  end


  def edit
    @switch_configuration = @current_network.switch_configurations.where(id: params[:id] || params[:switch_configuration][:id]).first
    if @switch_configuration.present?
      @switch_hardware_parts = HardwarePart.switch_hardware_parts
      @selected_hw_part =  @switch_configuration.hardware_part || @switch_hardware_parts.first 
      @switch_port_configurations = [@switch_configuration.switch_port_configurations.build]
      @aps_collection = SwitchConfiguration.grouped_collection_of_aps(@current_network, @selected_hw_part.id, @switch_configuration.id)
      @port_configurations = @switch_configuration.switch_port_configurations.map {|d| [d.port_number, d]}.inject({}) {|h,d| h[d[0]] = d[1];h}
      @port_configuration = @switch_configuration.switch_port_configurations.build
      @ports_configured = @switch_configuration.switch_port_configurations.where("port_number <= ?", @selected_hw_part.port_count)

      render :new
    else
      flash[:info] = "Requested switch configuration is not found"
      redirect_to switch_configurations_path
    end
  end

  # GET /switch_configurations/1
  # GET /switch_configurations/1.json
  def update
    if @switch_configuration.update(switch_configuration_params.merge({"sw_mac_oui" => switch_configuration_params['sw_mac_oui'] || []}))
      flash[:success] = "Successfully updated Switch Configuration"
      json_data = {data: @switch_configuration.json_build , status: 200}        
    else
      flash[:error] = "Oops! there was some problem updating Switch Configuration"
      json_data = {message: "Switch Configuration is not updated (Reason: #{@switch_configuration.errors.full_messages}).", status: 422}
    end
    if request.format.json?
      render json: json_data, status: json_data[:status]
    else
      redirect_to edit_switch_configuration_path @switch_configuration
    end
  end

  # DELETE /switch_configurations/1
  # DELETE /switch_configurations/1.json
  def destroy
    if @switch_configuration.destroy
      flash[:success] = "Successfully deleted Switch Configuration"
      json_data = {data: {}, status: 200}
    else
      flash[:error] = "Oops! there was some problem in deleting Switch Configuration"
      Rails.logger.warn "#{@switch_configuration.errors.full_messages}"
      json_data = {message: "Switch Configuration is not deleted. Please try again.", status: 422}
    end
    if request.format.json?
      render json: json_data, status: json_data[:status]
    else
      redirect_to home_path(@current_network.id, :t => "sw")
    end
  end

  def change_network
    network = current_user.location_networks.find_by_id(params[:id])
    unless network.present?
    network = current_user.location_networks.first
    flash[:notice] = "Your network has been changed to #{network.network_name}"
    end
    current_user.current_network = network.id
    @current_network = current_user.current_network
    logger.info("Current Network in show <<<<<<#{@current_network.id}") unless @current_network.blank?
    routers
    render :action => :access_point
  end

  def get_switches_by_model
    hw_details = HardwarePart.switch_hardware_parts.where(id: params[:switch_model]).first
    if hw_details.present?
      devices = SwitchConfiguration.grouped_collection_of_aps(@current_network, params[:switch_model].to_i, params[:switch_configuration_id])
  
      render json: {success: true, data: {switches: devices, hw_details: {:name => hw_details.name, :port_count => hw_details.port_count, :wired_count => hw_details.wired_count}}}, status: 200
    else
      render json: {success: false, msg: "Selected switch model is Invalid. Please select the correct model."}, status: 404
    end
  end

  private

  def switch_configuration_params
    params.require(:switch_configuration).permit(:switch_model, :id, :organisation_id, :location_network_id, :hardware_part_id, :switch_port_configurations_attributes => [:port_status, :link_negotiation, :speed, :power, :poe, :vlan, :port_type, :acl_mac, :mac_filter_policy, :acl_mac_list, :id, :_destroy], associated_resources: [], :sw_mac_oui => [:macaddress, :mask, :vlanid, :priority])
  end

  def find_switch_configuration
    @switch_configuration = SwitchConfiguration.where(id: params[:id] || params[:switch_configuration][:id]).last
    if @switch_configuration.blank?
      flash[:notice] = "Requested switch configuration is not found."
      respond_to do |format|
        format.html { redirect_to switch_configurations_url }
        format.json { render status: 404, json: {success: false, message: "Requested switch configuraion is not found. please check and try again."} }
      end
    end
  end
end
