package monitor

import (
	"sync"
	"time"
)

type Monitor struct {
	peers       map[string]bool
	mutex       sync.RWMutex
	heartbeatFn func(peer string) bool
}

func NewMonitor(heartbeatFn func(peer string) bool) *Monitor {
	return &Monitor{
		peers:       make(map[string]bool),
		heartbeatFn: heartbeatFn,
	}
}

func (m *Monitor) Start(peers []string) {
	for _, peer := range peers {
		go func(p string) {
			for {
				m.updateStatus(p)
				time.Sleep(5 * time.Second)
			}
		}(peer)
	}
}

func (m *Monitor) updateStatus(peer string) {
	alive := m.heartbeatFn(peer)
	m.mutex.Lock()
	defer m.mutex.Unlock()
	m.peers[peer] = alive
}

func (m *Monitor) IsPeerOnline(peer string) bool {
	m.mutex.RLock()
	defer m.mutex.RUnlock()
	return m.peers[peer]
}
