package app

import (
	"fmt"

	"code.fbi.h-da.de/danet/gosdn/controller/store"
	"github.com/google/uuid"
)

// ManagementService is the app service.
type ManagementService interface {
	Register(string, string) (*App, error)
	Deregister(string) error
}

// Service manages apps and their access to the event system.
type Service struct {
	store ManagementStore
}

// NewAppService creates a new app service.
func NewAppService(store ManagementStore) ManagementService {
	return &Service{
		store: store,
	}
}

// Register checks if the app already exists and if not creates a new one.
func (a *Service) Register(appName, token string) (*App, error) {
	if token != "SecurePresharedToken" {
		return nil, fmt.Errorf("token not valid")
	}

	exisitingApp, err := a.store.Get(store.Query{ID: uuid.Nil, Name: appName})
	if err != nil {
		if exisitingApp.ID == uuid.Nil {
			return a.createNewApp(appName)
		}

		return nil, err
	}

	return &exisitingApp, nil
}

// Deregister deregisters an app.
func (a *Service) Deregister(appName string) error {
	app, err := a.store.Get(store.Query{Name: appName})
	if err != nil {
		return err
	}

	err = a.store.Delete(app)
	if err != nil {
		return err
	}

	return nil
}

func (a *Service) createNewApp(appName string) (*App, error) {
	app := App{
		ID:                     uuid.New(),
		Name:                   appName,
		EventSystemCredentials: "amqp://guest:guest@127.0.0.1:5672",
	}

	// generate app credentials
	err := a.store.Add(app)
	if err != nil {
		return nil, err
	}

	return &app, nil
}
