package starmap

import (
	"b612.me/notify"
)

func (kv *RemoteKv) clientOnline() error {
	return kv.reconnect()
}

func (kv *RemoteKv) MustGet(key string) interface{} {
	result, _ := kv.Get(key)
	return result
}

func (kv *RemoteKv) Get(key interface{}) (interface{}, error) {
	if err := kv.clientOnline(); err != nil {
		return nil, err
	}
	keyCode, err := notify.ToMsgVal(key)
	if err != nil {
		return nil, err
	}
	data, err := kv.client.SendWait("get", keyCode, kv.readTimeout)
	if err != nil {
		return nil, err
	}
	rp, err := data.Value.ToInterface()
	if err != nil {
		return nil, err
	}
	reply := rp.(kvMsg)
	return reply.Value, reply.Err
}

func (kv *RemoteKv) Store(key interface{}, value interface{}) error {
	if err := kv.clientOnline(); err != nil {
		return err
	}
	encodeData, err := notify.ToMsgVal(kvMsg{
		Key:   key,
		Value: value,
		Err:   nil,
	})
	if err != nil {
		return err
	}
	data, err := kv.client.SendWait("store", encodeData, kv.readTimeout)
	if err != nil {
		return err
	}
	rp, err := data.Value.ToInterface()
	if err != nil {
		return err
	}
	return rp.(kvMsg).Err
}

func (kv *RemoteKv) Delete(key interface{}) error {
	if err := kv.clientOnline(); err != nil {
		return err
	}
	keyCode, err := notify.ToMsgVal(key)
	if err != nil {
		return err
	}
	data, err := kv.client.SendWait("delete", keyCode, kv.readTimeout)
	if err != nil {
		return err
	}
	rp, err := data.Value.ToInterface()
	if err != nil {
		return err
	}
	return rp.(kvMsg).Err
}

func (kv *RemoteKv) Exists(key interface{}) bool {
	if err := kv.clientOnline(); err != nil {
		return false
	}
	keyCode, err := notify.ToMsgVal(key)
	if err != nil {
		return false
	}
	data, err := kv.client.SendWait("exists", keyCode, kv.readTimeout)
	if err != nil {
		return false
	}
	rp, err := data.Value.ToInterface()
	if err != nil {
		return false
	}
	reply := rp.(kvMsg)
	return reply.Value.(bool)
}
