package cache

import (
	"fmt"

	gocache "github.com/patrickmn/go-cache"

	"github.com/pingcap-inc/clinic/pkg/db/model"
)

var KibanaCache = newKibanaCache()

type kibanaCache struct {
	cache *gocache.Cache
}

type KibanaUser struct {
	Name     string
	Password string
}

func newKibanaCache() *kibanaCache {
	return &kibanaCache{
		cache: gocache.New(gocache.NoExpiration, gocache.NoExpiration),
	}
}

func (kc *kibanaCache) Set(orgID uint, u *KibanaUser) {
	kc.cache.Set(fmt.Sprintf("%d", orgID), u, gocache.NoExpiration)
}

func (kc *kibanaCache) Delete(orgID uint) {
	kc.cache.Delete(fmt.Sprintf("%d", orgID))
}

func (kc *kibanaCache) Init() error {
	infos, err := model.ListAlLKibanaInfo()
	if err != nil {
		return err
	}

	for _, info := range infos {
		kc.Set(info.OrgID, &KibanaUser{
			Name:     info.User,
			Password: info.Password,
		})
	}

	return nil
}

func (kc *kibanaCache) Get(orgID string) *KibanaUser {
	v, ok := kc.cache.Get(orgID)
	if !ok {
		return nil
	}

	return v.(*KibanaUser)
}
