class WiredConfigsController < 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,:except => [:get_vlan_id], if: Proc.new { |c| !c.request.format.json? }
  before_action :set_wired_config, only: [:show, :update, :destroy]
  # before_action :find_radius_configuration, :only => [:new, :edit]
  load_and_authorize_resource :class => WiredConfig
  check_policy_for :create, :update, :destroy, with: WiredConfig, id_param: :id
  skip_authorize_resource :only => [:new, :create,:get_vlan_id]
  
  def index
    @network_wired_configs = params[:id] ? @current_network.wired_configs.where(id: params[:id]) : @current_network.wired_configs

    render json: {data: {wired_configurations: @network_wired_configs.map(&:json_build)}}
  end

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

  def new
    @network_wired_config = @current_network.wired_configs.build(APPLICATION["defaults"]["wired_config_default_val"])
    @aps_collection = WiredConfig.grouped_collection_of_ap_and_tags @current_network
    #v_lan = current_user.organisation.v_lans.where(:v_lan_id => '1').last
    #current_user.organisation.v_lans.create(APPLICATION["defaults"]["v_lan_config_default_val"]) if v_lan.blank? || (v_lan.present? && v_lan.try(:wired_config).present?)
    @vlan_ids = @current_network.network_ssids.includes(:v_lan).pluck(:v_lan_id).uniq.compact.join(',')
  end

  def update
    # network_wired_config = WiredConfig.find(params[:id])
    if @network_wired_config.update_attributes(wired_config_params)
      flash[:success] = "Successfully updated Switch Configuration #{@network_wired_config.name}"
      json_data = {data: @network_wired_config.json_build , status: 200}
    else
      if @network_wired_config.errors.messages.keys.include?(:"firmware_conflict")
        flash[:error] = "Oops! there was some problem in updating Switch Configuration #{@network_wired_config.errors.messages[:"firmware_conflict"]}"
        json_data = {message: "Wired Configuration is not updated (Reason: #{@network_wired_config.errors.messages[:"firmware_conflict"]})." , status: 422}
      else
        flash[:error] = "Oops! there was some problem in updating Switch Configuration"
        json_data = {message: "Wired Configuration is not updated. Please try again." , status: 422}
      end  
      Rails.logger.warn "#{@network_wired_config.errors.full_messages}"
    end
    if request.format.json?
      render json: json_data, status: json_data[:status]
    else
      redirect_to  home_path(@current_network)
    end
  end

  def create
    wc = @current_network.wired_configs.new(wired_config_params)
    if wc.save
      flash[:success] = "Successfully created Switch Configuration"
      json_data = {data: wc.json_build , status: 200}
    else
      if wc.errors.messages.keys.include?(:"firmware_conflict")
        flash[:error] = "Oops! there was some problem in creating Switch Configuration #{wc.errors.messages[:"firmware_conflict"]}"
        json_data = {message: "Wired Configuration is not updated (Reason: #{wc.errors.messages[:"firmware_conflict"]})." , status: 422}
      else
        flash[:error] = "Oops! there was some problem in creating Switch Configuration"
        json_data = {message: "Wired Configuration is not updated. Please try again." , status: 422}
      end
      Rails.logger.warn "#{wc.errors.full_messages}"
    end
    if request.format.json?
      render json: json_data, status: json_data[:status]
    else
      redirect_to  home_path(@current_network)
    end
  end

  def edit
    redirect_to home_path(@current_network) if params[:id].blank?
    @vlan_ids = @current_network.network_ssids.includes(:v_lan).pluck(:v_lan_id).uniq.compact.join(',')
    @network_wired_config = @current_network.wired_configs.find_by_id(params[:id])
    if @network_wired_config.present?
      @port_configs = @network_wired_config.port_configs
    else
      render file: "#{Rails.root}/public/404", layout: true, status: :not_found
    end
    if @network_wired_config.blank?
      redirect_to home_path(@current_network)
    else
      @aps_collection = WiredConfig.grouped_collection_of_ap_and_tags @current_network, @network_wired_config
    end
  end

  def destroy
    if @network_wired_config.destroy
      flash[:success] = "Successfully deleted Switch Configuration #{@network_wired_config.name}"
      json_data = {data: {}, status: 200}
    else
      flash[:notice] = "Oops! there was some problem in deleting Wired Configuration"
      Rails.logger.warn "#{@network_wired_config.errors.full_messages}"
      json_data = {message: "Wired 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) and return
    end
  end

  def get_vlan_id
    v_lan_ids = []
     RouterInventory.where(id: params[:mac_ids].split(',')).each do |ri|
        v_lan_ids << ri.associated_network_ssids.includes(:v_lan).pluck(:v_lan_id)
     end
     v_lan_ids = v_lan_ids.flatten.compact
     render :json => v_lan_ids
  end

  private

    def set_wired_config
      @network_wired_config = @current_network.wired_configs.where(id: params[:id]).last

      if @network_wired_config.blank?
        if request.format.json?
          render json: {message: "Wired Configuration not found for requested network. Please check and try again.", status: 404}, status: 404
        else
          flash[:notice] = "Wired Configuration not found for requested network. Please check and try again."
          redirect_to home_path(@current_network)
        end
      end
    end

    def wired_config_params
      params.require(:wired_config).permit(:name,:nat,:auth_radius_id,:acc_radius_enabled,:acc_radius_id,:acl_mac,:mac_filter_policy,:acl_mac_list,:captive_portal,:splash_url,:wallgarden,:walled_garden_range,:overwrite_success_url,:success_url,:dhcp_range_start,:dhcp_range_end,:dhcp_relay_server,:dhcp_lease_time,:ip_address,:subnet_mask, :per_user_qos, :enable_ssid_qos, :ssid_qos,:max_association, :dns_mode, :dns_primary, :dns_secondary, :wna, :default_idle_timeout, :default_interim_time,:custom_port,:v_lan_ids => [],:associated_resources => [], :dhcp_mappings => [:IPADDR,:MAC],:dhcp_ranges => [:START,:END],:port_configs => [:PID,:PVID,:TAG,:DIS,:VID => []])
    end

    def find_radius_configuration
      @r_config = current_user.organisation.radiuses
      @r_acc = current_user.organisation.radius_accountings
    end
end
