# frozen_string_literal: false

# ----------------------------------------------------------------------------
#
#     ***     AUTO GENERATED CODE    ***    AUTO GENERATED CODE     ***
#
# ----------------------------------------------------------------------------
#
#     This file is automatically generated by Magic Modules and manual
#     changes will be clobbered when the file is regenerated.
#
#     Please read more about how to change this file in README.md and
#     CONTRIBUTING.md located at the root of this package.
#
# ----------------------------------------------------------------------------
require 'gcp_backend'
class ComputeInstances < GcpResourceBase
  name 'google_compute_instances'
  desc 'Instance plural resource'
  supports platform: 'gcp'

  attr_reader :table

  filter_table_config = FilterTable.create

  filter_table_config.add(:can_ip_forwards, field: :can_ip_forward)
  filter_table_config.add(:cpu_platforms, field: :cpu_platform)
  filter_table_config.add(:creation_timestamps, field: :creation_timestamp)
  filter_table_config.add(:deletion_protections, field: :deletion_protection)
  filter_table_config.add(:disks, field: :disks)
  filter_table_config.add(:guest_accelerators, field: :guest_accelerators)
  filter_table_config.add(:hostnames, field: :hostname)
  filter_table_config.add(:ids, field: :id)
  filter_table_config.add(:label_fingerprints, field: :label_fingerprint)
  filter_table_config.add(:labels, field: :labels)
  filter_table_config.add(:metadata, field: :metadata)
  filter_table_config.add(:machine_types, field: :machine_type)
  filter_table_config.add(:min_cpu_platforms, field: :min_cpu_platform)
  filter_table_config.add(:names, field: :name)
  filter_table_config.add(:network_interfaces, field: :network_interfaces)
  filter_table_config.add(:schedulings, field: :scheduling)
  filter_table_config.add(:service_accounts, field: :service_accounts)
  filter_table_config.add(:shielded_instance_configs, field: :shielded_instance_config)
  filter_table_config.add(:statuses, field: :status)
  filter_table_config.add(:status_messages, field: :status_message)
  filter_table_config.add(:tags, field: :tags)
  filter_table_config.add(:zones, field: :zone)

  filter_table_config.connect(self, :table)

  def initialize(params = {})
    super(params.merge({ use_http_transport: true }))
    @params = params
    @table = fetch_wrapped_resource('items')
  end

  def fetch_wrapped_resource(wrap_path)
    # fetch_resource returns an array of responses (to handle pagination)
    result = @connection.fetch_all(product_url, resource_base_url, @params, 'Get')
    return if result.nil?

    # Conversion of string -> object hash to symbol -> object hash that InSpec needs
    converted = []
    result.each do |response|
      next if response.nil? || !response.key?(wrap_path)
      response[wrap_path].each do |hash|
        hash_with_symbols = {}
        hash.each_key do |key|
          name, value = transform(key, hash)
          hash_with_symbols[name] = value
        end
        converted.push(hash_with_symbols)
      end
    end

    converted
  end

  def transform(key, value)
    return transformers[key].call(value) if transformers.key?(key)

    [key.to_sym, value]
  end

  def transformers
    {
      'canIpForward' => ->(obj) { [:can_ip_forward, obj['canIpForward']] },
      'cpuPlatform' => ->(obj) { [:cpu_platform, obj['cpuPlatform']] },
      'creationTimestamp' => ->(obj) { [:creation_timestamp, obj['creationTimestamp']] },
      'deletionProtection' => ->(obj) { [:deletion_protection, obj['deletionProtection']] },
      'disks' => ->(obj) { [:disks, GoogleInSpec::Compute::Property::InstanceDisksArray.parse(obj['disks'], to_s)] },
      'guestAccelerators' => ->(obj) { [:guest_accelerators, GoogleInSpec::Compute::Property::InstanceGuestAcceleratorsArray.parse(obj['guestAccelerators'], to_s)] },
      'hostname' => ->(obj) { [:hostname, obj['hostname']] },
      'id' => ->(obj) { [:id, obj['id']] },
      'labelFingerprint' => ->(obj) { [:label_fingerprint, obj['labelFingerprint']] },
      'labels' => ->(obj) { [:labels, obj['labels']] },
      'metadata' => ->(obj) { [:metadata, obj['metadata']] },
      'machineType' => ->(obj) { [:machine_type, obj['machineType']] },
      'minCpuPlatform' => ->(obj) { [:min_cpu_platform, obj['minCpuPlatform']] },
      'name' => ->(obj) { [:name, obj['name']] },
      'networkInterfaces' => ->(obj) { [:network_interfaces, GoogleInSpec::Compute::Property::InstanceNetworkInterfacesArray.parse(obj['networkInterfaces'], to_s)] },
      'scheduling' => ->(obj) { [:scheduling, GoogleInSpec::Compute::Property::InstanceScheduling.new(obj['scheduling'], to_s)] },
      'serviceAccounts' => ->(obj) { [:service_accounts, GoogleInSpec::Compute::Property::InstanceServiceAccountsArray.parse(obj['serviceAccounts'], to_s)] },
      'shieldedInstanceConfig' => ->(obj) { [:shielded_instance_config, GoogleInSpec::Compute::Property::InstanceShieldedInstanceConfig.new(obj['shieldedInstanceConfig'], to_s)] },
      'status' => ->(obj) { [:status, obj['status']] },
      'statusMessage' => ->(obj) { [:status_message, obj['statusMessage']] },
      'tags' => ->(obj) { [:tags, GoogleInSpec::Compute::Property::InstanceTags.new(obj['tags'], to_s)] },
      'zone' => ->(obj) { [:zone, obj['zone']] },
    }
  end

  # Handles parsing RFC3339 time string
  def parse_time_string(time_string)
    time_string ? Time.parse(time_string) : nil
  end

  def identifiers
    params = %w{project zone name}

    result = []
    @table.each do |item|
      combo = item.merge(@params)
      item_identifiers = {}
      params.each do |param|
        item_identifiers[param.to_sym] = combo[param.to_sym]
      end
      result.push(item_identifiers)
    end
    result
  end

  private

  def product_url
    'https://www.googleapis.com/compute/v1/'
  end

  def resource_base_url
    'projects/{{project}}/zones/{{zone}}/instances'
  end
end
