package raftNode

import (
	"encoding/json"
	"sync"
)

type TreeData struct {
	lock    *sync.RWMutex
	dataLen int64
	Data    map[string]interface{}
}

func (that *TreeData) Copy() ([]byte, error) {
	that.lock.RLock()
	defer that.lock.RUnlock()
	if that.dataLen == 0 {
		return nil, nil
	}
	_byte := []byte{}
	_byte, _err := json.Marshal(that.Data)
	if _err != nil {
		return nil, _err
	}
	return _byte, nil
}

func (that *TreeData) List() []interface{} {
	that.lock.RLock()
	defer that.lock.RUnlock()
	_list := []interface{}{}
	for _, _v := range that.Data {
		_list = append(_list, _v)
	}
	return _list
}

func (that *TreeData) Get(key string) interface{} {
	that.lock.RLock()
	defer that.lock.RUnlock()
	_data, _ok := that.Data[key]
	if !_ok {
		return ""
	}
	return _data
}

func (that *TreeData) Set(key string, value string) {
	that.lock.Lock()
	defer that.lock.Unlock()
	if _, _ok := that.Data[key]; !_ok {
		that.dataLen++
	}
	that.Data[key] = value
}

func (that *TreeData) Del(key string) {
	that.lock.Lock()
	defer that.lock.Unlock()
	if _, _ok := that.Data[key]; !_ok {
		that.dataLen--
	}
	delete(that.Data, key)
}

//Restore 从快照中恢复到内存
func (that *TreeData) Restore(data []byte) error {
	that.lock.Lock()
	defer that.lock.Unlock()
	if _err := json.Unmarshal(data, &that.Data); _err != nil {
		return _err
	}
	return nil
}
