package internals

import (
	"fmt"
	"log"
	"strconv"

	"github.com/syndtr/goleveldb/leveldb"
)

// CacheConn -
type CacheConn struct {
	CacheDB *leveldb.DB
}

// SetCache -
func (c *CacheConn) SetCache(cacheDB *leveldb.DB) {
	c.CacheDB = cacheDB
}

// GetCachedDataIntSub -
func (c *CacheConn) GetCachedDataIntSub(key int32, subkey string) int32 {
	return c.GetCachedDataInt(fmt.Sprintf("%d.%s", key, subkey))
}

// GetCachedDataSub -
func (c *CacheConn) GetCachedDataSub(key int32, subkey string) string {
	return c.GetCachedData(fmt.Sprintf("%d.%s", key, subkey))
}

// GetCachedDataIntSub64 -
func (c *CacheConn) GetCachedDataIntSub64(key int64, subkey string) int32 {
	return c.GetCachedDataInt(fmt.Sprintf("%d.%s", key, subkey))
}

// GetCachedDataSub64 -
func (c *CacheConn) GetCachedDataSub64(key int64, subkey string) string {
	return c.GetCachedData(fmt.Sprintf("%d.%s", key, subkey))
}

// GetCachedDataInt -
func (c *CacheConn) GetCachedDataInt(key string) int32 {
	strVal := c.GetCachedData(key)

	intVal, convErr := strconv.ParseInt(strVal, 10, 32)
	if convErr != nil {
		return -1
	}

	return int32(intVal)
}

// GetCachedData -
func (c *CacheConn) GetCachedData(key string) string {

	response, err := c.CacheDB.Get([]byte(key), nil)
	if err != nil {
		return ""
	}

	return string(response[:])
}

// PutCacheDataIntSub -
func (c *CacheConn) PutCacheDataIntSub(key int32, subkey string, value int32) {
	c.PutCacheDataSub(key, subkey, fmt.Sprintf("%d", value))
}

// PutCacheDataSub -
func (c *CacheConn) PutCacheDataSub(key int32, subkey string, value string) {
	c.PutCacheData(fmt.Sprintf("%d.%s", key, subkey), value)
}

// PutCacheDataIntSub64 -
func (c *CacheConn) PutCacheDataIntSub64(key int64, subkey string, value int32) {
	c.PutCacheDataSub64(key, subkey, fmt.Sprintf("%d", value))
}

// PutCacheDataSub64 -
func (c *CacheConn) PutCacheDataSub64(key int64, subkey string, value string) {
	c.PutCacheData(fmt.Sprintf("%d.%s", key, subkey), value)
}

// PutCacheData -
func (c *CacheConn) PutCacheData(key string, value string) {
	err := c.CacheDB.Put([]byte(key), []byte(value), nil)
	if err != nil {
		log.Fatal(err)
	}
}
