package raftNode2

import (
	"sync"
)

var modulusMap = map[int64]int64{
	0: 0,
	1: 1,
	2: 1,
	3: 1,
	4: 1,
	5: 1,
	6: 1,
	7: 1,
	8: 1,
	9: 1,
}

type uidCacheAction struct {
	uidMap  map[string]uidData //内存游标
	uidLock sync.Mutex         //锁
}

func (that *uidCacheAction) Clear() {
	that.uidLock.Lock()
	defer that.uidLock.Unlock()
	that.uidMap = map[string]uidData{}
}

func (that *uidCacheAction) IsExist(key string) bool {
	that.uidLock.Lock()
	defer that.uidLock.Unlock()
	_, _ok := that.uidMap[key]
	return _ok
}

func (that *uidCacheAction) InitStart(name string, id, preDomain int64) {
	that.uidLock.Lock()
	defer that.uidLock.Unlock()
	_newData := uidData{
		name:      name,
		uid:       id,
		preDomain: preDomain,
	}
	that.uidMap[name] = _newData
}

//newID id缓存（最新的id值）
func (that *uidCacheAction) newID(name string, id, preDomain int64) (int64, int64) {
	that.uidLock.Lock()
	defer that.uidLock.Unlock()
	//初始值
	_newID := id
	_preDomain := preDomain
	//
	_data, _ok := that.uidMap[name]
	if _ok {
		if _data.preDomain >= _preDomain {
			_newID = modulusID(_data.uid)
			_preDomain = _data.preDomain
		}
	}
	//
	_newData := uidData{
		name:      name,
		uid:       _newID,
		preDomain: _preDomain,
	}
	that.uidMap[name] = _newData
	//异步落地到raft分布式存储里
	uidAsyncSave.uidUpdateSign(_newData)
	return _newID, _preDomain
}

func modulusID(id int64) int64 {
	//追加1
	for {
		id = id + 1
		_mod := id % 10
		if _modStatus, _ := modulusMap[_mod]; _modStatus == 1 {
			return id
		}
	}
}
