package plugins

import (
	"cwtch.im/cwtch/event"
	"git.openprivacy.ca/openprivacy/log"
	"time"
)

const heartbeatTickTime = 60 * time.Second

type heartbeat struct {
	bus       event.Manager
	queue     event.Queue
	breakChan chan bool
}

func (hb *heartbeat) Start() {
	go hb.run()
}

func (hb *heartbeat) Id() PluginID {
	return HEARTBEAT
}

func (hb *heartbeat) Shutdown() {
	hb.breakChan <- true
	hb.queue.Shutdown()
}

func (hb *heartbeat) run() {
	log.Debugf("running heartbeat trigger plugin")
	for {
		select {
		case <-time.After(heartbeatTickTime):
			// no fuss, just trigger the beat.
			hb.bus.Publish(event.NewEvent(event.Heartbeat, map[event.Field]string{}))
			continue
		case <-hb.breakChan:
			log.Debugf("shutting down heartbeat plugin")
			return
		}
	}
}

// NewHeartbeat returns a Plugin that when started will trigger heartbeat checks on a regular interval
func NewHeartbeat(bus event.Manager) Plugin {
	cr := &heartbeat{bus: bus, queue: event.NewQueue(), breakChan: make(chan bool, 1)}
	return cr
}
