package svc

import (
	"encoding/json"

	"golib/v2/features/mo"
	"golib/v2/infra/ii"
	"golib/v2/log"
)

var (
	svc *Service
)

func InitDefault(client *mo.Client, items ii.Items, perms ii.Permission, log log.Printer) {
	svc = new(Service)
	svc.Client = client
	svc.Items = items
	svc.Perms = perms
	svc.Log = log
	svc.cache = NewCache(items)
	svc.refreshCh = make(chan *ii.ItemInfo, 1024)
	go svc.handleRefresh()
}

func Items() ii.Items {
	return svc.GetItems()
}

func DbClient() *mo.Client {
	return svc.Client
}

func HasItem(name ii.Name) (*ii.ItemInfo, bool) {
	info, ok := svc.HasItem(name)
	if !ok {
		return nil, false
	}
	b, err := json.Marshal(info)
	if err != nil {
		panic(err)
	}
	var itemInfo ii.ItemInfo
	if err = json.Unmarshal(b, &itemInfo); err != nil {
		panic(err)
	}
	return &itemInfo, true
}

func AddItemCache(name ii.Name, user ii.User) {
	svc.cache.AddItem(name)
	service := Svc(user)
	rows, err := service.Find(name, mo.D{})
	if err != nil {
		panic(err)
	}
	svc.cache.SetData(name, rows)
}

func Svc(u ii.User) *Service {
	s := svc
	s.User = u
	return s
}
