package monitor

import (
	"sync"
	"time"
)

const (
	refreshStreamPeriod    = 20 * time.Second
	refreshViewcountPeriod = 45 * time.Second
)

func refreshUsher(refreshFunc func(int) bool, sleepTime time.Duration) {
	for {
		if isMaster() || *forceMaster {
			channels, _ := db.AllChannels()
			var wg sync.WaitGroup
			for _, channel := range channels {
				if channel.Active {
					wg.Add(1)
					go func(channelId int) {
						defer wg.Done()
						refreshFunc(channelId)
					}(channel.ID)
				}
			}
			wg.Wait()
		}
		time.Sleep(sleepTime)
	}
}

func refreshStreams() {
	fn := usherService.RefreshStream
	refreshUsher(fn, refreshStreamPeriod)
}

func refreshViewcounts() {
	fn := usherService.RefreshViewcount
	refreshUsher(fn, refreshViewcountPeriod)
}
