package shallow_collaborative_area

import (
	"cloud.o-forge.io/core/oc-lib/dbs"
	"cloud.o-forge.io/core/oc-lib/dbs/mongo"
	"cloud.o-forge.io/core/oc-lib/models/utils"
)

type shallowSharedWorkspaceMongoAccessor struct {
	utils.AbstractAccessor
}

func New() *shallowSharedWorkspaceMongoAccessor {
	return &shallowSharedWorkspaceMongoAccessor{}
}

func (wfa *shallowSharedWorkspaceMongoAccessor) DeleteOne(id string) (utils.DBObject, int, error) {
	return wfa.GenericDeleteOne(id, wfa)
}

func (wfa *shallowSharedWorkspaceMongoAccessor) UpdateOne(set utils.DBObject, id string) (utils.DBObject, int, error) {
	return wfa.GenericUpdateOne(set.(*ShallowCollaborativeArea), id, wfa, &ShallowCollaborativeArea{})
}

func (wfa *shallowSharedWorkspaceMongoAccessor) StoreOne(data utils.DBObject) (utils.DBObject, int, error) {
	return wfa.GenericStoreOne(data.(*ShallowCollaborativeArea), wfa)
}

func (wfa *shallowSharedWorkspaceMongoAccessor) CopyOne(data utils.DBObject) (utils.DBObject, int, error) {
	return wfa.StoreOne(data)
}

func (wfa *shallowSharedWorkspaceMongoAccessor) LoadOne(id string) (utils.DBObject, int, error) {
	var sharedWorkspace ShallowCollaborativeArea
	res_mongo, code, err := mongo.MONGOService.LoadOne(id, wfa.GetType())
	if err != nil {
		wfa.Logger.Error().Msg("Could not retrieve " + id + " from db. Error: " + err.Error())
		return nil, code, err
	}
	res_mongo.Decode(&sharedWorkspace)
	return &sharedWorkspace, 200, nil
}

func (wfa shallowSharedWorkspaceMongoAccessor) LoadAll() ([]utils.ShallowDBObject, int, error) {
	objs := []utils.ShallowDBObject{}
	res_mongo, code, err := mongo.MONGOService.LoadAll(wfa.GetType())
	if err != nil {
		wfa.Logger.Error().Msg("Could not retrieve any from db. Error: " + err.Error())
		return nil, code, err
	}
	var results []ShallowCollaborativeArea
	if err = res_mongo.All(mongo.MngoCtx, &results); err != nil {
		return nil, 404, err
	}
	for _, r := range results {
		objs = append(objs, &r)
	}
	return objs, 200, nil
}

func (wfa *shallowSharedWorkspaceMongoAccessor) Search(filters *dbs.Filters, search string) ([]utils.ShallowDBObject, int, error) {
	objs := []utils.ShallowDBObject{}
	if (filters == nil || len(filters.And) == 0 || len(filters.Or) == 0) && search != "" {
		filters = &dbs.Filters{
			Or: map[string][]dbs.Filter{
				"abstractobject.name": {{Operator: dbs.LIKE.String(), Value: search}},
			},
		}
	}
	res_mongo, code, err := mongo.MONGOService.Search(filters, wfa.GetType())
	if err != nil {
		wfa.Logger.Error().Msg("Could not store to db. Error: " + err.Error())
		return nil, code, err
	}
	var results []ShallowCollaborativeArea
	if err = res_mongo.All(mongo.MngoCtx, &results); err != nil {
		return nil, 404, err
	}
	for _, r := range results {
		objs = append(objs, &r)
	}
	return objs, 200, nil
}
