package api

import (
	"log"
	"net"
	"strings"
	"time"

	"deevirt.fr/compute/cmd/compute_api/proto"
	"deevirt.fr/compute/pkg/config"
	clientv3 "go.etcd.io/etcd/client/v3"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
)

func Server() {
	config, _ := config.NewConfig()

	//listen on the port
	lis, err := net.Listen("tcp", ":8080")
	if err != nil {
		log.Fatalf("Failed to start server %v", err)
	}

	etcd, err := clientv3.New(clientv3.Config{
		Endpoints:   strings.Split(config.EtcdURI, ","),
		DialTimeout: 5 * time.Second,
	})
	if err != nil {
		log.Fatalf("Error connexion to etcd: %v", err)
	}
	defer etcd.Close()

	grpcServer := grpc.NewServer()
	proto.RegisterDomainServer(grpcServer, &Domain{
		Config: config,
		Etcd:   etcd,
	})
	reflection.Register(grpcServer)
	log.Printf("Server started at %v", lis.Addr())
	if err := grpcServer.Serve(lis); err != nil {
		log.Fatalf("Failed to start: %v", err)
	}
}
