package raftNode

import (
	"sync"
)

//uidAsyncSaveAction 异步落地uid游标到数据表
type uidAsyncSaveAction struct {
	uidUpdateMap  map[string]*uidData
	uidUpdateLock sync.Mutex
}

func (that *uidAsyncSaveAction) Clear() {
	that.uidUpdateLock.Lock()
	defer that.uidUpdateLock.Unlock()
	that.uidUpdateMap = map[string]*uidData{}
}

//getUidUpdate 获取最新的id值
func (that *uidAsyncSaveAction) getUidUpdate(name string) *uidData {
	that.uidUpdateLock.Lock()
	defer that.uidUpdateLock.Unlock()
	if _, _ok := that.uidUpdateMap[name]; _ok {
		return that.uidUpdateMap[name]
	}
	return nil
}

func (that *uidAsyncSaveAction) initUidUpdate(name string, id, preDomain int64) {
	that.uidUpdateLock.Lock()
	defer that.uidUpdateLock.Unlock()
	that.uidUpdateMap[name] = &uidData{
		uid:       id,
		name:      name,
		preDomain: preDomain,
	}
}

//setUidUpdate 设置更新id值
func (that *uidAsyncSaveAction) setUidUpdate(name string, id, preDomain int64) *uidData {
	that.uidUpdateLock.Lock()
	defer that.uidUpdateLock.Unlock()
	_data, _ok := that.uidUpdateMap[name]
	if !_ok {
		that.uidUpdateMap[name] = &uidData{
			uid:       id,
			name:      name,
			preDomain: preDomain,
		}
	} else {
		if preDomain > _data.preDomain {
			_data.uid = id
			_data.preDomain = preDomain
		}
		if _data.preDomain == preDomain {
			if id > _data.uid {
				_data.uid = id
			}
		}
		that.uidUpdateMap[name] = _data
	}
	return that.uidUpdateMap[name]
}

//uidUpdateSign id更新信号
func (that *uidAsyncSaveAction) uidUpdateSign(data uidData) {
	//叠加器，保证最新
	uidStack.stack(data)
	//异步，保证响应的效率
	select {
	case _data := <-uidStack:
		//fmt.Println("======== aaa =======", _data.name, _data.uid, _data.preDomain)
		go func() {
			_up := that.setUidUpdate(_data.name, _data.uid, _data.preDomain)
			if _up.uid == _data.uid && _up.preDomain == _data.preDomain {
				//fmt.Println("======== bbb =======", _data.name, _data.uid, _data.preDomain)
				updateStack.Stack(_data.name)
			}
		}()
	default:
	}
}
