package jxutils

import (
	"sync"
	"time"

	"git.rosy.net.cn/baseapi/utils"
)

type SyncMapWithTimeout struct {
	sync.Map
	timers sync.Map
}

func (m *SyncMapWithTimeout) StoreWithTimeout(key, value interface{}, timeout time.Duration) {
	m.Map.Store(key, value)
	m.timers.Store(key, utils.AfterFuncWithRecover(timeout, func() {
		m.Delete(key)
	}))
}

func (m *SyncMapWithTimeout) Delete(key interface{}) {
	m.Map.Delete(key)
	if value, ok := m.timers.Load(key); ok {
		timer := value.(*time.Timer)
		timer.Stop()
		m.timers.Delete(key)
	}
}
