package ports

import (
	"fmt"

	"code.fbi.h-da.de/danet/gosdn/controller/customerrs"
	"code.fbi.h-da.de/danet/gosdn/controller/interfaces/networkelement"
	"code.fbi.h-da.de/danet/gosdn/controller/nucleus/database"
	query "code.fbi.h-da.de/danet/gosdn/controller/store"

	"github.com/google/uuid"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// Store defines a PortStore interface.
type Store interface {
	Add(Port) error
	Update(Port) error
	Delete(Port) error
	Get(query.Query) (Port, error)
	GetAll() ([]Port, error)
}

// DatabasePortStore is a database store for ports.
type DatabasePortStore struct {
	storeName string
}

// NewDatabasePortStore returns a PortStore.
func NewDatabasePortStore() Store {
	return &DatabasePortStore{
		storeName: fmt.Sprint("port-store.json"),
	}
}

// Get takes a Ports's UUID or name and returns the port.
func (s *DatabasePortStore) Get(query query.Query) (Port, error) {
	var loadedPort Port

	if query.ID.String() != "" {
		loadedPort, err := s.getByID(query.ID)
		if err != nil {
			return loadedPort, customerrs.CouldNotFindError{ID: query.ID, Name: query.Name}
		}

		return loadedPort, nil
	}

	loadedPort, err := s.getByName(query.Name)
	if err != nil {
		return loadedPort, customerrs.CouldNotFindError{ID: query.ID, Name: query.Name}
	}

	return loadedPort, nil
}

func (s *DatabasePortStore) getByID(idOfPort uuid.UUID) (loadedPort Port, err error) {
	client, ctx, cancel := database.GetMongoConnection()
	defer cancel()
	defer func() {
		if ferr := client.Disconnect(ctx); ferr != nil {
			fErrString := ferr.Error()
			err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString)
		}
	}()

	idAsByteArray, _ := idOfPort.MarshalBinary()

	db := client.Database(database.DatabaseName)
	collection := db.Collection(s.storeName)
	result := collection.FindOne(ctx, bson.D{primitive.E{Key: "_id", Value: idAsByteArray}})
	if result == nil {
		return loadedPort, customerrs.CouldNotFindError{ID: idOfPort}
	}

	err = result.Decode(&loadedPort)
	if err != nil {
		return loadedPort, customerrs.CouldNotMarshallError{Identifier: idOfPort, Type: loadedPort, Err: err}
	}

	return loadedPort, nil
}

func (s *DatabasePortStore) getByName(nameOfPort string) (loadedPort Port, err error) {
	client, ctx, cancel := database.GetMongoConnection()
	defer cancel()
	defer func() {
		if ferr := client.Disconnect(ctx); ferr != nil {
			fErrString := ferr.Error()
			err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString)
		}
	}()

	db := client.Database(database.DatabaseName)
	collection := db.Collection(s.storeName)
	result := collection.FindOne(ctx, bson.D{primitive.E{Key: "name", Value: nameOfPort}})
	if result == nil {
		return loadedPort, customerrs.CouldNotFindError{Name: nameOfPort}
	}

	err = result.Decode(&loadedPort)
	if err != nil {
		return loadedPort, customerrs.CouldNotMarshallError{Identifier: nameOfPort, Type: loadedPort, Err: err}
	}

	return loadedPort, nil
}

// GetAll returns all stored ports.
func (s *DatabasePortStore) GetAll() (loadedPorts []Port, err error) {
	client, ctx, cancel := database.GetMongoConnection()
	defer cancel()
	defer func() {
		if ferr := client.Disconnect(ctx); ferr != nil {
			fErrString := ferr.Error()
			err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString)
		}
	}()

	db := client.Database(database.DatabaseName)
	collection := db.Collection(s.storeName)

	cursor, err := collection.Find(ctx, bson.D{})
	if err != nil {
		return []Port{}, err
	}
	defer func() {
		if ferr := cursor.Close(ctx); ferr != nil {
			fErrString := ferr.Error()
			err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString)
		}
	}()

	err = cursor.All(ctx, &loadedPorts)
	if err != nil {
		return loadedPorts, customerrs.CouldNotMarshallError{Type: loadedPorts, Err: err}
	}

	return loadedPorts, nil
}

// Add adds a port to the port store.
func (s *DatabasePortStore) Add(port Port) (err error) {
	client, ctx, cancel := database.GetMongoConnection()
	defer cancel()
	defer func() {
		if ferr := client.Disconnect(ctx); ferr != nil {
			fErrString := ferr.Error()
			err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString)
		}
	}()

	_, err = client.Database(database.DatabaseName).
		Collection(s.storeName).
		InsertOne(ctx, port)
	if err != nil {
		return customerrs.CouldNotCreateError{Identifier: port.ID, Type: port, Err: err}
	}

	return nil
}

// Update updates a existing port.
func (s *DatabasePortStore) Update(port Port) (err error) {
	var updatedLoadedNetworkElement networkelement.LoadedNetworkElement

	client, ctx, cancel := database.GetMongoConnection()
	defer cancel()
	defer func() {
		if ferr := client.Disconnect(ctx); ferr != nil {
			fErrString := ferr.Error()
			err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString)
		}
	}()

	update := bson.D{primitive.E{Key: "$set", Value: port}}

	upsert := false
	after := options.After
	opt := options.FindOneAndUpdateOptions{
		Upsert:         &upsert,
		ReturnDocument: &after,
	}

	err = client.Database(database.DatabaseName).
		Collection(s.storeName).
		FindOneAndUpdate(
			ctx, bson.M{"_id": port.ID.String()}, update, &opt).
		Decode(&updatedLoadedNetworkElement)
	if err != nil {
		return customerrs.CouldNotUpdateError{Identifier: port.ID, Type: port, Err: err}
	}

	return nil
}

// Delete deletes a port from the port store.
func (s *DatabasePortStore) Delete(port Port) (err error) {
	client, ctx, cancel := database.GetMongoConnection()
	defer cancel()
	defer func() {
		if ferr := client.Disconnect(ctx); ferr != nil {
			fErrString := ferr.Error()
			err = fmt.Errorf("InternalError=%w DeferError=%+s", err, fErrString)
		}
	}()

	db := client.Database(database.DatabaseName)
	collection := db.Collection(s.storeName)
	_, err = collection.DeleteOne(ctx, bson.D{primitive.E{Key: port.ID.String()}})
	if err != nil {
		return err
	}

	return nil
}
