package playhead

import (
	"time"

	"code.justin.tv/video/spectre/backend"
)

var (
	playheadInitializePeriod = 5 * time.Second
)

var SyncRunning bool

func Sync(b *backend.Backend) {
	go func() {
		for {
			syncPlayheads(b)
			time.Sleep(playheadInitializePeriod)
		}
	}()
}

// syncPlayheads makes sure that a playhead exists for a channel iff the channel is marked active
func syncPlayheads(b *backend.Backend) {
	chs, _ := b.AllChannels()
	for _, ch := range chs {
		p, found := GetPlayhead(ch.ID)
		if (!ch.Active && found) || (found && p.Channel.Nonce() != ch.Nonce()) {
			go FreezePlayhead(ch.ID)
		}

	}
	if !SyncRunning {
		SyncRunning = true
	}
}
