package grpcServer

import (
	"context"
	"net"

	"google.golang.org/grpc"

	"github.com/coredhcp/coredhcp/grpc_server/dhcpServer"
	"github.com/coredhcp/coredhcp/logger"
	rangeplugin "github.com/coredhcp/coredhcp/plugins/range"
)

var log = logger.GetLogger("grpc")

type staServer struct {
	dhcpServer.UnimplementedStaServiceServer
}

func (s *staServer) GetSta(ctx context.Context, req *dhcpServer.MacAddr) (*dhcpServer.StaDhcpInfo, error) {
	record := rangeplugin.GetRecord(req.Mac)
	if record != nil {
		return &dhcpServer.StaDhcpInfo{
			Ip:       record.IP.String(),
			Hostname: record.Hostname,
		}, nil
	} else {
		return nil, nil
	}
}

type dhcpService struct {
	dhcpServer.UnimplementedDhcpServiceServer
}

func (d *dhcpService) GetDhcp(ctx context.Context, req *dhcpServer.EmptyRequest) (dhcpInfo *dhcpServer.DhcpInfo, err error) {
	return rangeplugin.GetDhcpInfo()
}

func Run() {
	lis, err := net.Listen("tcp", "127.0.0.1:50051")
	if err != nil {
		log.Errorf("failed to listen: %v", err)
	}

	s := grpc.NewServer()

	dhcpServer.RegisterStaServiceServer(s, &staServer{})
	dhcpServer.RegisterDhcpServiceServer(s, &dhcpService{})

	if err := s.Serve(lis); err != nil {
		log.Errorf("failed to serve: %v", err)
	}
}