package grpcserver

import (
	"fmt"
	"github.com/rs/zerolog/log"
	"github.com/spf13/viper"
	"google.golang.org/grpc"
	"net"
	"solidarity-service/handler"
	"solidarity-service/servers/grpc/proto"
)

type SolidarityServiceServerImpl struct {
	Handler *handler.SolidarityServiceHandler
	proto.UnimplementedSolidarityServiceServer
}

func NewSolidarityServiceServer(handler *handler.SolidarityServiceHandler) *SolidarityServiceServerImpl {
	return &SolidarityServiceServerImpl{
		Handler: handler,
	}
}

func Run(done chan error, cfg *viper.Viper, handler *handler.SolidarityServiceHandler) {
	var (
		address = cfg.GetString("services.grpc.ip") + ":" + cfg.GetString("services.grpc.port")
	)

	server := grpc.NewServer()
	proto.RegisterSolidarityServiceServer(server, NewSolidarityServiceServer(handler))
	l, err := net.Listen("tcp", address)
	if err != nil {
		log.Fatal().Err(err)
		return
	}
	if err := server.Serve(l); err != nil {
		fmt.Println("gRPC service ended")
		done <- err
	}
}
