class CommandsController < ApplicationController
  before_action :authenticate_user!
  before_action :set_command, only: [:show, :edit, :update, :destroy]
  load_and_authorize_resource :class => Command
  skip_load_resource :only => [:create]

  # GET /commands
  # GET /commands.json
  def index
    if params[:id].blank?
      @command = Command.new
      @ar = []
    else
      @command = current_user.commands_full.find(params[:id]) #Command.find(params[:id])
      @ar = SnmpConfig.tagging_lists(@command.aps)
    end
    @commands = current_user.commands_full.includes(:router_inventories) rescue []
    @lists =  current_user.aps_inventory_tags #AclGroup.aps_inventory_tags(current_user.organisation)
  end

  # GET /commands/1
  # GET /commands/1.json
  def show
  end

  def showing_status

  end
  # GET /commands/new
  def new
    @command = Command.new
  end

  # GET /commands/1/edit
  def edit
  end

  # POST /commands
  # POST /commands.json
  def create
    create_update(params[:command])
    redirect_to :action=>:index
  end

  def create_update(command)
    ri = []
    command[:aps].each do |router|
      id = router.split(":")
      if id[0] == 'AP'
        ri << current_user.router_inventories_full.find_by_id(id[1].to_i)
      elsif id[0] == 'network'
        ri += current_user.router_inventories_full.find_all_by_location_network_id(id[1].to_i)
      elsif id[0] == 'tag'
        ri += current_user.router_inventories_full.tagged_with(ActsAsTaggableOn::Tag.find(id[1]).name)
      end
    end
    ri.uniq!
    ri.each do |r|
      router = "AP:#{r.id.to_s}"
      if ((params[:command]["init"].present?) && (params[:command]["init"] == "true")) 
       Command.init_cmd(r,command[:commands])
      else
        command[:commands].split("||").each do |com|
          cmd = Command.where({:aps => router, :commands => com, :status => "pending"}).last
          if cmd.blank?
            cmd = Command.create({:aps => router, :commands => com, :status => "pending"})
            flash[:success] = "Your Payload was setup Successfully"
          else
            flash[:success] = "Your Payload was updated Successfully"
          end
          r.commands << cmd if cmd.router_inventories.blank?
          cmd.set_redis(r)
  
          flash[:success] = "Your payload has been setup Successfully"
        end
      end
    end
  end
  # PATCH/PUT /commands/1
  # PATCH/PUT /commands/1.json
  def update
    create_update(params[:command])
    redirect_to :action=>:index
  end

  # DELETE /commands/1
  # DELETE /commands/1.json
  def destroy
    unless @command.blank?
      ri = @command.router_inventories.first
      if @command.pending?
        @command.destroy
        @command.set_redis(ri)
        flash[:success] = "Your Payload was destroyed Successfully"
      else
        flash[:warning] = "You can't destroy the Payload which is already consumed."
         Rails.logger.warn "#{@command.errors.full_messages}"
      end
    end
    redirect_to commands_path
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_command
      @command = Command.where(:id => params[:id]).first
      if @command.blank?
        flash[:warning] = "Requested Payload not found"
        redirect_to :action=>:index
      end
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def command_params
      params.require(:command).permit(:commands, :init, :aps => [])
    end
end
