require 'src/filters'
require "logger"
require "active_support"
require "active_support/core_ext"

class TemplateService
  attr_reader :path

  def initialize(klass, path)
    @klass = klass
    @path = cleanup_path(path, :SERVICE).freeze
  end

  def name
    klass.name.dup
  end

  def factory_method_name
    factory_name.gsub("ServiceClient", "").underscore
  end

  def is_suitable_for_template_at_verison?(version)
    return false if name.include?("Operations::Client")
    return true if name.start_with?("Google::Ads::GoogleAds::#{version}")

    false
  end

  def rpc_request_type_for(rpc)
    rpc_requests.select { |rpc_name|
      rpc_name == rpc
    }.values.first.input
  end

  def rpc_names
    rpc_requests.keys
  end

  private

  attr_reader :klass

  def rpc_requests
    # pnlpn@ was here on 2019-12-04:
    # rpc_descs is a hash with uppercased RPC names typed as symbols, e.g.
    # (:Search) so we underscore so that we're safe for ruby method names
    Hash[stub_class.rpc_descs.map { |desc, value|
      [desc.to_s.underscore.to_sym, value]
    }]
  end

  def factory_name
    name.split("::")[-2..-1].join("")
  end

  def stub_class
    # pnlpn@ was here on 2019-12-04:
    # the new Gapic service type doesn't cleanly expose the request type that
    # it needs the request to be, so this method gets it.

    # this stanza goes from the gax generated FooService::Client to
    # FooService::Service and requires it.
    stub_path = path.gsub("\/client.rb", "_services_pb.rb")
    require stub_path

    # drop "Client" off the end of the constant name, and require the "Service",
    # which is the stub class generated by the GRPC protoc compiler, this does
    # have enough information for us to recover the RPC information
    Kernel.const_get(
      name.split("::")[0...-1].join("::") + "::Service"
    )
  end
end
