# 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'
require 'google/compute/property/instancegroup_named_ports'

# A provider to manage Compute Engine resources.
class ComputeInstanceGroup < GcpResourceBase
  name 'google_compute_instance_group'
  desc 'InstanceGroup'
  supports platform: 'gcp'

  attr_reader :params
  attr_reader :creation_timestamp
  attr_reader :description
  attr_reader :id
  attr_reader :name
  attr_reader :named_ports
  attr_reader :network
  attr_reader :region
  attr_reader :subnetwork
  attr_reader :zone

  def initialize(params)
    super(params.merge({ use_http_transport: true }))
    @params = params
    @fetched = @connection.fetch(product_url(params[:beta]), resource_base_url, params, 'Get')
    parse unless @fetched.nil?
  end

  def parse
    @creation_timestamp = parse_time_string(@fetched['creationTimestamp'])
    @description = @fetched['description']
    @id = @fetched['id']
    @name = @fetched['name']
    @named_ports = GoogleInSpec::Compute::Property::InstanceGroupNamedPortsArray.parse(@fetched['namedPorts'], to_s)
    @network = @fetched['network']
    @region = @fetched['region']
    @subnetwork = @fetched['subnetwork']
    @zone = @fetched['zone']
  end

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

  def exists?
    !@fetched.nil?
  end

  def to_s
    "InstanceGroup #{@params[:name]}"
  end

  def port_name
    find_named_ports(:name)
  end
  RSpec::Matchers.alias_matcher :has_port_name, :be_allow_port_name

  def port_value
    find_named_ports(:port)
  end
  RSpec::Matchers.alias_matcher :has_port_value, :be_allow_port_value

  def find_named_ports(key = :name)
    # check all name/port values for a match
    @named_ports.each do |named_port|
      next if !defined?(named_port.item[key]) || named_port.item[key].nil?
      return named_port.item[key]
    end
    false
  end

  private

  def product_url(beta = false)
    if beta
      'https://compute.googleapis.com/compute/beta/'
    else
      'https://compute.googleapis.com/compute/v1/'
    end
  end

  def resource_base_url
    'projects/{{project}}/zones/{{zone}}/instanceGroups/{{name}}'
  end
end
