package raftNode2

import (
	"PPOSUtils/utils"
	"sync"
)

var (
	raftNode     *RaftNode
	activeTasker *utils.Tasker
	//
	uidStack    uidStackChan = make(chan uidData, 1)
	updateStack              = utils.NewStackChanPool()
	//
	activeMapLock    sync.Mutex
	activeMap        map[string]int64
	activeSessionMap map[string]int64
	//
	uidCache = &uidCacheAction{
		uidMap: map[string]uidData{},
	}
	//
	uidAsyncSave = &uidAsyncSaveAction{
		uidUpdateMap: map[string]*uidData{},
	}
)

func init() {
	activeTasker = new(utils.Tasker)
	go activeTasker.Run(1, 2)
	//最新uid，异步落地到分布式存储
	go func() {
		_map := map[string]uidData{}
		for {
			_slice := updateStack.Get()
			for _, _v := range _slice {
				_name := utils.ToString(_v)
				_uidData := uidAsyncSave.getUidUpdate(_name)
				_cacheUid, _ok := _map[_name]
				//
				if _ok && _uidData.uid == _cacheUid.uid && _uidData.preDomain == _cacheUid.preDomain {
					continue
				}
				_map[_name] = uidData{
					name:      _name,
					uid:       _uidData.uid,
					preDomain: _uidData.preDomain,
				}
				//
				if raftNode != nil {
					if _err := raftNode.SetUUid(_name, _uidData.uid, utils.ToString(_uidData.preDomain)); _err != nil {
						//记录日志，并发出kill信号
					}
				}
			}
		}
	}()
}

type uidStackChan chan uidData

//Stack 实现无阻塞的信道“叠加器”方法
func (that uidStackChan) stack(value uidData) {
	//_uid := value.uid
	for {
		select {
		case that <- value:
			return
		case _old := <-that:
			//
			if _old.preDomain > value.preDomain {
				value = _old
				continue
			}
			if _old.preDomain == value.preDomain {
				if _old.uid > value.uid {
					value = _old
					continue
				}
			}
		}
	}
}
