package registration

import (
	"context"
	"time"

	"code.fbi.h-da.de/danet/gosdn/api/go/gosdn/app"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

// Register registers a new app at the control plane.
func Register(gosdnAddress, name, token string) (string, error) {
	conn, err := grpc.Dial(gosdnAddress, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		return "", err
	}

	ctx := context.Background()
	appService := app.NewAppServiceClient(conn)

	request := &app.AppRegisterRequest{
		Timestamp: time.Now().UnixNano(),
		Appname:   name,
		Token:     token,
	}

	response, err := appService.Register(ctx, request)
	if err != nil {
		return "", err
	}

	return response.Queueconnection, nil
}
