/*
 *
 * Copyright 2015 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

// Package main implements a server for Greeter service.
package main

import (
	"context"
	"flag"
	"fmt"
	"net"
	"net/http"

	grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	pb "github.com/tidbcloud/tiinf/examples/tigrpc/helloworld/helloworld"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"github.com/tidbcloud/tiinf/monitor/titracing"
	tigrpc "github.com/tidbcloud/tiinf/transport/tigrpc/server"
	"go.uber.org/zap"
)

var (
	port = flag.Int("port", 50051, "The server port")
)

// server is used to implement helloworld.GreeterServer.
type server struct {
	pb.UnimplementedGreeterServer
}

// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
	tilog.Info(ctx, "Received message", zap.String("name", in.GetName()))
	return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil
}

func main() {
	flag.Parse()

	// Init trace provider
	_, err := titracing.InitJaeger("exmaple")
	if err != nil {
		panic(err)
	}

	// Run metrics server
	go func() {
		http.Handle("/metrics", promhttp.Handler())
		err = http.ListenAndServe(":9090", nil)
		if err != nil {
			panic(err)
		}
	}()

	ctx := context.Background()
	lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
	if err != nil {
		tilog.Fatal(ctx, "failed to listen", zap.Error(err))
	}
	s := tigrpc.NewServer(
		tigrpc.WithDefault(),
		// example about how to add custom grpc inteceptors
		tigrpc.WithUnaryInterceptors(
			grpc_ctxtags.UnaryServerInterceptor(),
		),
	)
	pb.RegisterGreeterServer(s, &server{})
	if err := s.Serve(lis); err != nil {
		tilog.Fatal(ctx, "failed to serve", zap.Error(err))
	}
}
