<commit_before>require 'rest_client'
require 'optparse'
require 'filesize'
require 'morpheus/cli/cli_command'
require 'morpheus/cli/mixins/infrastructure_helper'

class Morpheus::Cli::SubnetsCommand
  include Morpheus::Cli::CliCommand
  include Morpheus::Cli::InfrastructureHelper

  set_command_name :subnets

  register_subcommands :list, :get, :add, :update, :remove
  # register_subcommands :'types' => :list_subnet_types
  register_subcommands :'types' => :list_subnet_types
  register_subcommands :'get-type' => :get_subnet_type

  # set_default_subcommand :list
  
  def initialize()
    # @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance
  end

  def connect(opts)
    @api_client = establish_remote_appliance_connection(opts)
    @networks_interface = @api_client.networks
    @network_types_interface = @api_client.network_types
    @subnets_interface = @api_client.subnets
    @subnet_types_interface = @api_client.subnet_types
    @clouds_interface = @api_client.clouds
    @options_interface = @api_client.options
  end

  def handle(args)
    handle_subcommand(args)
  end

  def list(args)
    options = {}
    params = {}
    optparse = Morpheus::Cli::OptionParser.new do |opts|
      opts.banner = subcommand_usage("")
      build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
      opts.on( '-c', '--cloud CLOUD', "Filter by Cloud" ) do |val|
        options[:cloud] = val
      end
      opts.on( '--network NETWORK', '--network NETWORK', "Filter by Network" ) do |val|
        options[:network] = val
      end
      opts.footer = "List subnets."
    end
    optparse.parse!(args)
    if args.count > 0
      raise_command_error "wrong number of arguments, expected 0 and got (#{args.count}) #{args}\n#{optparse}"
    end
    connect(options)
    
    params.merge!(parse_list_options(options))
    network = nil
    if options[:network]
      network = find_network_by_name_or_id(options[:network])
      if network
        params['networkId'] = network['id']
      else
        return 1, "Network not found"
      end
    end
    cloud = nil
    if options[:cloud]
      cloud = find_cloud_by_name_or_id(options[:cloud])
      if cloud
        params['zoneId'] = cloud['id']
      else
        return 1, "Cloud not found"
      end
    end
    

    exit_code, err = 0, nil

    @subnets_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @subnets_interface.dry.list(params)
      return exit_code, err
    end
    json_response = @subnets_interface.list(params)
    subnets = json_response["subnets"]

    render_result = render_with_format(json_response, options, 'subnets')
    return exit_code, err if render_result

    title = "Morpheus Subnets"
    subtitles = []
    if network
      subtitles << "Network: #{network['name']}"
    end
    if cloud
      subtitles << "Cloud: #{cloud['name']}"
    end
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    
    if subnets.empty?
      print cyan,"No subnets found.",reset,"\n"
    else
      subnet_columns = {
        "ID" => 'id',
        "Name" => 'name',
        #"Description" => 'description',
        "Network" => lambda {|it| it['network']['name'] rescue it['network'] },
        "Type" => lambda {|it| it['type']['name'] rescue it['type'] },
        "Cloud" => lambda {|it| it['zone']['name'] rescue it['zone'] },
        "CIDR" => lambda {|it| it['cidr'] },
        "DHCP" => lambda {|it| format_boolean(it['dhcpServer']) },
        "Visibility" => lambda {|it| it['visibility'].to_s.capitalize },
        "Active" => lambda {|it| format_boolean(it['active']) },
        "Tenants" => lambda {|it| it['tenants'] ? it['tenants'].collect {|it| it['name'] }.uniq.join(', ') : '' },
      }
      print cyan
      print as_pretty_table(subnets, subnet_columns)
      print_results_pagination(json_response, {:label => "subnet", :n_label => "subnets"})
    end
    print reset,"\n"
    return exit_code, err  
    
  end


  def get(args)
    options = {}
    optparse = Morpheus::Cli::OptionParser.new do |opts|
      opts.banner = subcommand_usage("[network] [subnet]")
      build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
      opts.footer = "Get details about a subnet." + "\n" +
                    "[subnet] is required. This is the name or id of a subnet."
    end
    optparse.parse!(args)
    if args.count != 1
      raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args}\n#{optparse}"
    end
    connect(options)
    begin
      subnet_id = nil
      if args[0].to_s =~ /\A\d{1,}\Z/
        subnet_id = args[0].to_i
      else
        subnet = find_subnet_by_name(args[0])
        return 1, "Security Group not found" if subnet.nil?
        subnet_id = subnet['id']
      end<commit_msg>Fix subnets get -j<commit_after>require 'rest_client'
require 'optparse'
require 'filesize'
require 'morpheus/cli/cli_command'
require 'morpheus/cli/mixins/infrastructure_helper'

class Morpheus::Cli::SubnetsCommand
  include Morpheus::Cli::CliCommand
  include Morpheus::Cli::InfrastructureHelper

  set_command_name :subnets

  register_subcommands :list, :get, :add, :update, :remove
  # register_subcommands :'types' => :list_subnet_types
  register_subcommands :'types' => :list_subnet_types
  register_subcommands :'get-type' => :get_subnet_type

  # set_default_subcommand :list
  
  def initialize()
    # @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance
  end

  def connect(opts)
    @api_client = establish_remote_appliance_connection(opts)
    @networks_interface = @api_client.networks
    @network_types_interface = @api_client.network_types
    @subnets_interface = @api_client.subnets
    @subnet_types_interface = @api_client.subnet_types
    @clouds_interface = @api_client.clouds
    @options_interface = @api_client.options
  end

  def handle(args)
    handle_subcommand(args)
  end

  def list(args)
    options = {}
    params = {}
    optparse = Morpheus::Cli::OptionParser.new do |opts|
      opts.banner = subcommand_usage("")
      build_common_options(opts, options, [:list, :query, :json, :yaml, :csv, :fields, :dry_run, :remote])
      opts.on( '-c', '--cloud CLOUD', "Filter by Cloud" ) do |val|
        options[:cloud] = val
      end
      opts.on( '--network NETWORK', '--network NETWORK', "Filter by Network" ) do |val|
        options[:network] = val
      end
      opts.footer = "List subnets."
    end
    optparse.parse!(args)
    if args.count > 0
      raise_command_error "wrong number of arguments, expected 0 and got (#{args.count}) #{args}\n#{optparse}"
    end
    connect(options)
    
    params.merge!(parse_list_options(options))
    network = nil
    if options[:network]
      network = find_network_by_name_or_id(options[:network])
      if network
        params['networkId'] = network['id']
      else
        return 1, "Network not found"
      end
    end
    cloud = nil
    if options[:cloud]
      cloud = find_cloud_by_name_or_id(options[:cloud])
      if cloud
        params['zoneId'] = cloud['id']
      else
        return 1, "Cloud not found"
      end
    end
    

    exit_code, err = 0, nil

    @subnets_interface.setopts(options)
    if options[:dry_run]
      print_dry_run @subnets_interface.dry.list(params)
      return exit_code, err
    end
    json_response = @subnets_interface.list(params)
    subnets = json_response["subnets"]

    render_result = render_with_format(json_response, options, 'subnets')
    return exit_code, err if render_result

    title = "Morpheus Subnets"
    subtitles = []
    if network
      subtitles << "Network: #{network['name']}"
    end
    if cloud
      subtitles << "Cloud: #{cloud['name']}"
    end
    subtitles += parse_list_subtitles(options)
    print_h1 title, subtitles
    
    if subnets.empty?
      print cyan,"No subnets found.",reset,"\n"
    else
      subnet_columns = {
        "ID" => 'id',
        "Name" => 'name',
        #"Description" => 'description',
        "Network" => lambda {|it| it['network']['name'] rescue it['network'] },
        "Type" => lambda {|it| it['type']['name'] rescue it['type'] },
        "Cloud" => lambda {|it| it['zone']['name'] rescue it['zone'] },
        "CIDR" => lambda {|it| it['cidr'] },
        "DHCP" => lambda {|it| format_boolean(it['dhcpServer']) },
        "Visibility" => lambda {|it| it['visibility'].to_s.capitalize },
        "Active" => lambda {|it| format_boolean(it['active']) },
        "Tenants" => lambda {|it| it['tenants'] ? it['tenants'].collect {|it| it['name'] }.uniq.join(', ') : '' },
      }
      print cyan
      print as_pretty_table(subnets, subnet_columns)
      print_results_pagination(json_response, {:label => "subnet", :n_label => "subnets"})
    end
    print reset,"\n"
    return exit_code, err  
    
  end


  def get(args)
    options = {}
    optparse = Morpheus::Cli::OptionParser.new do |opts|
      opts.banner = subcommand_usage("[network] [subnet]")
      build_common_options(opts, options, [:json, :yaml, :csv, :fields, :dry_run, :remote])
      opts.footer = "Get details about a subnet." + "\n" +
                    "[subnet] is required. This is the name or id of a subnet."
    end
    optparse.parse!(args)
    if args.count != 1
      raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args}\n#{optparse}"
    end
    connect(options)
    exit_code, err = 0, nil
    begin
      subnet_id = nil
      if args[0].to_s =~ /\A\d{1,}\Z/
        subnet_id = args[0].to_i
      else
        subnet = find_subnet_by_name(args[0])
        return 1, "Security Group not found" if subnet.nil?
        subnet_id = subnet['id']
      end
{'fraction_non_alphanumeric': 0.1377055879047911, 'fraction_numerical': 0.0027581979773214833, 'mean_word_length': 3.1134453781512605, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 37, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4422165', 'n_tokens_mistral': 3343, 'n_tokens_neox': 3202, 'n_words': 730}