package task

import (
	"dsbqj-admin/model/mongo/version"
	"dsbqj-admin/pkg/util"
	"github.com/kamva/mgm/v3"
	"go.mongodb.org/mongo-driver/bson"
	"sync"
)

var VersionTask *Versions

type Versions struct {
	sync.Mutex
	VList util.SafeArray[*version.Version]
	VMap  util.SafeMap[string, *version.Version]
}

func VersionInit() *Versions {
	VersionTask = new(Versions)
	return VersionTask
}

func (this *Versions) Exec() {
	var versions = make([]*version.Version, 0)
	err := mgm.Coll(&version.Version{}).SimpleFind(&versions, bson.M{})
	if err == nil {
		// 重置
		this.VList.Flush()
		this.VList.PushMany(versions)
		this.VMap.Clear()
		for _, v := range versions {
			this.VMap.Set(v.Version, v)
		}
	}
}

func (this *Versions) Check(version string) *version.Version {
	data, ok := this.VMap.Get(version)
	if !ok { // 遍历列表
		for _, v := range this.VList.View() {
			if v.Default {
				data = v
				break
			}
		}
	}

	return data
}

func (this *Versions) Servers() []*version.Version {
	return this.VList.View()
}
