package api

import (
	"mesh/bus"
	"mesh/db/model"
	"mesh/db/repo"
	"time"

	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

func RegQueenMeshes(router *GinRouter) {

	CollectionName := "hubmeshes"
	CreateCRUD(router, "/hubmeshes", &CRUDOption{
		Collection: CollectionName,
		NewModel: func(c *gin.Context, apictx *ApiSession) (interface{}, error) {
			hub := &model.HubMesh{}
			c.ShouldBindJSON(hub)
			if len(hub.Name) < 1 {
				return nil, NewError("参数不合法!")
			}
			if len(hub.Thumbnail) < 1 {
				return nil, NewError("没有模型封面")
			}
			hub.CreateTime = time.Now()
			hub.UserId, _ = primitive.ObjectIDFromHex(apictx.User.Parent)
			if hub.UserId == primitive.NilObjectID {
				return nil, NewError("参数不合法!")
			}

			hub.DbName = "queenmeshes"
			if len(hub.Thumbnail) < 1 {
				hub.Thumbnail = "https://gd1.alicdn.com/imgextra/i2/0/O1CN01BXPA5l1H9VvVhEQQ7_!!0-item_pic.jpg_400x400.jpg"
			}
			ret, err := bus.TreeAddDefineMeshpack("queenmeshes", apictx.User.Parent, hub.Name)
			if err != nil {
				return nil, err
			}
			hub.Host = ret.Host
			hub.DefineId = ret.DefineId
			hub.Collection = ret.Collection
			hub.DbId = ret.DbId

			return hub, nil
		},

		EmtyModel: func(c *gin.Context, apictx *ApiSession) interface{} {
			return &model.HubMesh{}
		},
		SearchFilter: func(_ *gin.Context, apictx *ApiSession, _ map[string]interface{}) map[string]interface{} {
			userId, _ := primitive.ObjectIDFromHex(apictx.User.Parent)
			return map[string]interface{}{"userId": userId}
		},
		JWT:           true,
		SearchProject: []string{"name", "thumbnail", "createTime", "host", "dbid", "defineId"},
		DetailProject: []string{"name", "thumbnail", "createTime", "host", "dbid", "defineId"},
		Remove: func(_ *gin.Context, apictx *ApiSession, id string) (interface{}, error) {

			hub := &model.HubMesh{}
			err := repo.RepoSeachDoc2(apictx.CreateRepoCtx(), &repo.DocSearchOptions{CollectName: CollectionName, Query: repo.Map{"_id": id}}, hub)
			if err != nil {
				return nil, err
			}
			err = bus.TreeRemoveDefineMeshpack(hub.DbId, hub.DefineId)
			if err != nil {
				return nil, err
			}
			//todo queentree 添加删除状态
			return repo.RepoDeleteDoc(apictx.CreateRepoCtx(), CollectionName, id)
		},
	})
}
