package raftNode2

import (
	"time"
)

func cleanActiveLock() {
	activeMap = map[string]int64{}
	activeSessionMap = map[string]int64{}
}

//lockInitStart 初始化载入（分布式节点leader）
func lockInitStart(sessionID string, expire int64, domain string) {
	activeMapLock.Lock()
	defer activeMapLock.Unlock()
	if time.Now().Unix() > expire {
		raftNode.MDel("lock", sessionID)
		return
	}
	_active, _ok := activeMap[domain]
	if !_ok {
		_active = 0
	}
	activeSessionMap[sessionID] = expire
	activeMap[domain] = _active + 1
	go taskerOverLock(domain, sessionID, expire)
}

func taskerOverLock(domain, sessionID string, expire int64) {
	activeTasker.AddTask(int(expire), func() {
		sessionUnLock(domain, sessionID)
	})
}

//sessionLock 上锁
func sessionLock(domain, sessionID string, maxActive, expire int64) (bool, error) {
	activeMapLock.Lock()
	defer activeMapLock.Unlock()
	//
	_, _ok := activeSessionMap[sessionID]
	if _ok {
		return true, nil
	}
	//
	_active, _ok := activeMap[domain]
	if !_ok {
		_active = 0
		activeSessionMap[sessionID] = expire
	}
	if _active >= maxActive {
		return false, nil
	}
	//分布式存储
	if _err := raftNode.SetLock(sessionID, expire, domain); _err != nil {
		return false, _err
	}
	//fmt.Println(_active, maxActive, "===== lockActive =====", domain, sessionID, expire)
	//内存
	activeSessionMap[sessionID] = expire
	activeMap[domain] = _active + 1
	taskerOverLock(domain, sessionID, expire)
	return true, nil
}

//sessionUnLock 释放锁
func sessionUnLock(domain, sessionID string) error {
	func() {
		activeMapLock.Lock()
		defer activeMapLock.Unlock()
		_, _ok := activeSessionMap[sessionID]
		if !_ok {
			return
		}
		delete(activeSessionMap, sessionID)
		_active, _ok := activeMap[domain]
		if !_ok {
			activeMap[domain] = 0
			return
		}
		if _active > 1 {
			activeMap[domain] = _active - 1
		}
		if _active == 0 {
			delete(activeMap, domain)
		}
		//fmt.Println("====== unlockActive ======", activeMap[domain])
	}()
	return raftNode.MDel("lock", sessionID)
}
