package nucleus

import (
	"fmt"

	"code.fbi.h-da.de/danet/gosdn/controller/customerrs"
	"code.fbi.h-da.de/danet/gosdn/controller/interfaces/plugin"
	"code.fbi.h-da.de/danet/gosdn/controller/nucleus/database"
	"code.fbi.h-da.de/danet/gosdn/controller/store"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"

	log "github.com/sirupsen/logrus"
)

// DatabasePluginStore is used to store Plugins.
type DatabasePluginStore struct {
	pluginStoreName string
}

// Add adds a plugin.
func (s *DatabasePluginStore) Add(pluginToAdd plugin.Plugin) (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.pluginStoreName).
		InsertOne(ctx, pluginToAdd)
	if err != nil {
		if mongo.IsDuplicateKeyError(err) {
			return nil
		}

		return customerrs.CouldNotCreateError{Identifier: pluginToAdd.ID(), Type: pluginToAdd, Err: err}
	}

	return nil
}

// Update updates an existing plugin.
func (s *DatabasePluginStore) Update(pluginToUpdate plugin.Plugin) (err error) {
	var updatedLoadedPlugin plugin.LoadedPlugin

	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: pluginToUpdate}}

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

	err = client.Database(database.DatabaseName).
		Collection(s.pluginStoreName).
		FindOneAndUpdate(
			ctx, bson.M{"_id": pluginToUpdate.ID().String()}, update, &opt).
		Decode(&updatedLoadedPlugin)
	if err != nil {
		log.Printf("Could not update Plugin: %v", err)

		return customerrs.CouldNotUpdateError{Identifier: pluginToUpdate.ID(), Type: pluginToUpdate, Err: err}
	}

	return nil
}

// Delete deletes an plugin.
func (s *DatabasePluginStore) Delete(pluginToDelete plugin.Plugin) (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.pluginStoreName).
		DeleteOne(ctx, bson.D{primitive.E{Key: "_id", Value: pluginToDelete.ID().String()}})
	if err != nil {
		return customerrs.CouldNotDeleteError{Identifier: pluginToDelete.ID(), Type: pluginToDelete, Err: err}
	}

	return nil
}

// Get takes a SouthboundInterface's UUID or name and returns the SouthboundInterface. If the requested
// SouthboundInterface does not exist an error is returned.
func (s *DatabasePluginStore) Get(query store.Query) (loadedPlugin plugin.LoadedPlugin, 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)
		}
	}()

	log.Debugf("Plugin-Search-ID: %+v\n", query.ID.String())

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

	err = result.Decode(&loadedPlugin)
	if err != nil {
		log.Printf("Failed marshalling %v", err)

		return loadedPlugin, customerrs.CouldNotMarshallError{Identifier: query.ID, Type: loadedPlugin, Err: err}
	}

	return loadedPlugin, nil
}

// GetAll returns all plugin.
func (s *DatabasePluginStore) GetAll() (loadedPlugins []plugin.LoadedPlugin, 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.pluginStoreName)

	cursor, err := collection.Find(ctx, bson.D{})
	if err != nil {
		return nil, 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, &loadedPlugins)
	if err != nil {
		log.Printf("Failed marshalling %v", err)

		return nil, customerrs.CouldNotMarshallError{Type: loadedPlugins, Err: err}
	}

	return loadedPlugins, nil
}
