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

# A provider to manage Compute Engine resources.
class ComputeNetwork < GcpResourceBase
  name 'google_compute_network'
  desc 'Network'
  supports platform: 'gcp'

  attr_reader :params
  attr_reader :description
  attr_reader :gateway_ipv4
  attr_reader :id
  attr_reader :name
  attr_reader :subnetworks
  attr_reader :auto_create_subnetworks
  attr_reader :creation_timestamp
  attr_reader :routing_config
  attr_reader :peerings
  attr_reader :mtu

  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
    @description = @fetched['description']
    @gateway_ipv4 = @fetched['gatewayIPv4']
    @id = @fetched['id']
    @name = @fetched['name']
    @subnetworks = @fetched['subnetworks']
    @auto_create_subnetworks = @fetched['autoCreateSubnetworks']
    @creation_timestamp = parse_time_string(@fetched['creationTimestamp'])
    @routing_config = GoogleInSpec::Compute::Property::NetworkRoutingConfig.new(@fetched['routingConfig'], to_s)
    @peerings = GoogleInSpec::Compute::Property::NetworkPeeringsArray.parse(@fetched['peerings'], to_s)
    @mtu = @fetched['mtu']
  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
    "Network #{@params[:name]}"
  end

  def legacy?
    return false if @auto_create_subnetworks
    return false if !defined?(@gateway_ipv4)
    return false if !defined?(@network.ipv4_range)
    return false if @ipv4_range.nil?
    return false if @gateway_i_pv4.nil?
    true
  end

  def creation_timestamp_date
    @creation_timestamp
  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}}/global/networks/{{name}}'
  end
end
