package proto_socket

import (
	"sync"
	"time"
)

type HeartbeatTimer struct {
	mu       sync.Mutex
	timer    *time.Timer
	callback func()
}

func NewHeartbeatTimer(d time.Duration, cb func()) *HeartbeatTimer {
	h := &HeartbeatTimer{callback: cb}
	h.Reset(d)
	return h
}

func (h *HeartbeatTimer) Reset(d time.Duration) {
	h.mu.Lock()
	defer h.mu.Unlock()

	if h.timer != nil {
		h.timer.Stop()
	}
	h.timer = time.AfterFunc(d, h.callback)
}

func (h *HeartbeatTimer) Stop() {
	h.mu.Lock()
	defer h.mu.Unlock()

	if h.timer != nil {
		h.timer.Stop()
		h.timer = nil
	}
}
