# 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'

# A provider to manage Compute Engine resources.
class ComputeAddress < GcpResourceBase
  name 'google_compute_address'
  desc 'Address'
  supports platform: 'gcp'

  attr_reader :params
  attr_reader :address
  attr_reader :address_type
  attr_reader :creation_timestamp
  attr_reader :description
  attr_reader :id
  attr_reader :name
  attr_reader :purpose
  attr_reader :network_tier
  attr_reader :subnetwork
  attr_reader :users
  attr_reader :labels
  attr_reader :label_fingerprint
  attr_reader :status
  attr_reader :region

  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
    @address = @fetched['address']
    @address_type = @fetched['addressType']
    @creation_timestamp = parse_time_string(@fetched['creationTimestamp'])
    @description = @fetched['description']
    @id = @fetched['id']
    @name = @fetched['name']
    @purpose = @fetched['purpose']
    @network_tier = @fetched['networkTier']
    @subnetwork = @fetched['subnetwork']
    @users = @fetched['users']
    @labels = @fetched['labels']
    @label_fingerprint = @fetched['labelFingerprint']
    @status = @fetched['status']
    @region = @fetched['region']
  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
    "Address #{@params[:name]}"
  end

  def address_ip_exists
    !@address.nil?
  end

  # How many users are there for the address
  def user_count
    return 0 if @users.nil?
    @users.count
  end

  # Return the first user resource base name
  def user_resource_name
    @users.first.split('/').last
  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}}/regions/{{location}}/addresses/{{name}}'
  end
end
