package bus

import (
	"assetcenter/db"
	"assetcenter/db/repo"
	"context"
	"fmt"

	"github.com/nats-io/nats.go"
	"infish.cn/comm"
)

type TreeAddMatgroupReq struct {
	DbName     string
	Collection string
	Matgroup   *comm.AssetMatGroup
}

func RegTreeAssetAddMatgroup() *comm.NatsMsgReplyer {

	return &comm.NatsMsgReplyer{
		Subject: "tree.asset.add.matgroup",
		Entity:  func() interface{} { return &TreeAddMatgroupReq{} },
		Cb2: func(msg *nats.Msg, entity interface{}) (interface{}, error) {
			req, ok := entity.(*TreeAddMatgroupReq)
			if !ok {
				return nil, fmt.Errorf("参数错误")
			}
			if len(req.DbName) < 1 || len(req.Collection) < 1 {
				return nil, fmt.Errorf("DbName Collection 不能为空")
			}

			var CreateRepoCtx = func() *repo.RepoSession {
				return &repo.RepoSession{
					Ctx:    context.Background(),
					Client: db.MongoClient,
				}
			}
			return repo.RepoDbAddDoc(CreateRepoCtx(), req.DbName, req.Collection, req.Matgroup)
		},
	}
}

type AssetReq struct {
	DbHost     string
	DbName     string
	Collection string
	AssetId    string
}

func RegTreeAssetDetailMatgroup() *comm.NatsMsgReplyer {

	return &comm.NatsMsgReplyer{
		Subject: "tree.asset.detail.matgroup",
		Entity:  func() interface{} { return &AssetReq{} },
		Cb2: func(msg *nats.Msg, entity interface{}) (interface{}, error) {
			req, ok := entity.(*AssetReq)
			if !ok {
				return nil, fmt.Errorf("参数错误不是AssetReq类型")
			}
			if len(req.DbName) < 1 || len(req.Collection) < 1 || len(req.AssetId) < 1 {
				return nil, fmt.Errorf("DbName Collection AssetId 不能为空")
			}
			var CreateRepoCtx = func() *repo.RepoSession {
				return &repo.RepoSession{
					Ctx:    context.Background(),
					Client: db.MongoClient,
				}
			}
			out := &comm.AssetMatGroup{}
			ok, err := repo.RepoSeachDoc(CreateRepoCtx(), &repo.DocSearchOptions{Db: req.DbName, CollectName: req.Collection, Query: repo.Map{"_id": req.AssetId}}, out)
			if err != nil {
				return nil, err
			}
			if !ok {
				return nil, fmt.Errorf("查询的色卡不存在")
			}
			return out, nil
		},
	}
}