@*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * license agreements; and to You under the Apache License, version 2.0:
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * This file is part of the Apache Pekko project, which was derived from Akka.
 *@

@*
 * Copyright (C) 2018-2021 Lightbend Inc. <https://www.lightbend.com>
 *@

@(service: org.apache.pekko.grpc.gen.scaladsl.Service)

@org.apache.pekko.grpc.gen.Constants.DoNotEditComment
package @service.packageName

import org.apache.pekko
import pekko.annotation.ApiMayChange

import pekko.grpc.PekkoGrpcGenerated

@for(comment <- service.comment) {/**
@{java.util.regex.Pattern.compile("^\\s?(.*)$", java.util.regex.Pattern.MULTILINE).matcher(comment).replaceAll(" * $1")} */}
@@PekkoGrpcGenerated
trait @{service.name} {
  @for(method <- service.methods) {
  @for(comment <- method.comment) {/**
@{java.util.regex.Pattern.compile("^\\s?(.*)$", java.util.regex.Pattern.MULTILINE).matcher(comment).replaceAll("   * $1")}   */}
  def @{method.nameSafe}(in: @method.parameterType): @method.returnType
  }
}

@mapMethodType(methodType: org.apache.pekko.grpc.gen.MethodType) = {
  @if(methodType == org.apache.pekko.grpc.gen.Unary) { MethodDescriptor.MethodType.UNARY }
  @if(methodType == org.apache.pekko.grpc.gen.ClientStreaming) {MethodDescriptor.MethodType.CLIENT_STREAMING }
  @if(methodType == org.apache.pekko.grpc.gen.ServerStreaming) { MethodDescriptor.MethodType.SERVER_STREAMING }
  @if(methodType == org.apache.pekko.grpc.gen.BidiStreaming) {MethodDescriptor.MethodType.BIDI_STREAMING }
}

@@PekkoGrpcGenerated
object @{service.name} extends pekko.grpc.ServiceDescription {
  val name = "@service.grpcName"

  val descriptor: com.google.protobuf.Descriptors.FileDescriptor =
    @service.descriptor;

  object Serializers {
    import pekko.grpc.scaladsl.ScalapbProtobufSerializer
    @for(serializer <- service.serializers) {
    val @serializer.name = @serializer.init
    }
  }

  @@ApiMayChange
  @@PekkoGrpcGenerated
  object MethodDescriptors {
    import pekko.grpc.internal.Marshaller
    import io.grpc.MethodDescriptor
    import Serializers.@{service.scalaCompatConstants.WildcardImport}

    @for(method <- service.methods) {
    val @{method.name}Descriptor: MethodDescriptor[@method.inputTypeUnboxed, @method.outputTypeUnboxed] =
      MethodDescriptor.newBuilder()
        .setType(@mapMethodType(method.methodType))
        .setFullMethodName(MethodDescriptor.generateFullMethodName("@service.grpcName", "@method.grpcName"))
        .setRequestMarshaller(new Marshaller(@method.deserializer.name))
        .setResponseMarshaller(new Marshaller(@method.serializer.name))
        .setSampledToLocalTracing(true)
        .build()
    }
  }
}
