package server

import (
	"context"
	"time"

	apb "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/app"
	"code.fbi.h-da.de/danet/gosdn/controller/app"
)

// AppServer represents a AppServiceServer.
type AppServer struct {
	apb.UnimplementedAppServiceServer
	appService app.ManagementService
}

// NewAppServer creates a new AppServiceServer.
func NewAppServer(appService app.ManagementService) *AppServer {
	return &AppServer{
		appService: appService,
	}
}

// Register checks if the app already exists and if not creates a new one.
func (a *AppServer) Register(ctx context.Context, request *apb.AppRegisterRequest) (*apb.AppRegisterResponse, error) {
	app, err := a.appService.Register(request.Appname, request.Token)
	if err != nil {
		return &apb.AppRegisterResponse{
			Timestamp: time.Now().UnixNano(),
			Status:    apb.Status_STATUS_ERROR,
		}, err
	}

	return &apb.AppRegisterResponse{
		Timestamp:       time.Now().UnixNano(),
		Status:          apb.Status_STATUS_OK,
		Queueconnection: app.GetCredentials(),
	}, nil
}

// Deregister deregisters an app.
func (a *AppServer) Deregister(ctx context.Context, request *apb.AppDeregisterRequest) (*apb.AppDeregisterResponse, error) {
	err := a.appService.Deregister(request.Appname)
	if err != nil {
		return &apb.AppDeregisterResponse{
			Timestamp: time.Now().UnixNano(),
			Status:    apb.Status_STATUS_ERROR,
		}, err
	}

	return &apb.AppDeregisterResponse{
		Timestamp: time.Now().UnixNano(),
		Status:    apb.Status_STATUS_OK,
	}, nil
}
