package tilt

import (
	"context"
	"fmt"
	"log"
	"sync"
	"time"

	"github.com/getsentry/sentry-go"
)

var (
	C   chan Tilt
	hub *sentry.Hub
)

func init() {
	C = make(chan Tilt, 10)
	hub = sentry.CurrentHub().Clone()
}

func PollSensors(ctx context.Context, wg *sync.WaitGroup, interval time.Duration, scanDuration time.Duration) {
	defer wg.Done()
	defer hub.Flush(10 * time.Second)

	if interval < scanDuration {
		log.Fatal("Unable to use interval < scanDuration")
	}

	// Perform initial scan when booting
	scan(ctx, scanDuration)

	ticker := time.NewTicker(interval)
	for {
		select {
		case <-ticker.C:
			scan(ctx, scanDuration)

		case <-ctx.Done():
			return
		}
	}
}

func scan(ctx context.Context, timeout time.Duration) {
	scanner := NewScanner()
	scanner.Scan(ctx, timeout)

	for _, t := range scanner.Tilts() {
		color := string(t.Color())
		metricGravity.WithLabelValues(color).Set(t.Gravity())
		metricTemp.WithLabelValues(color).Set(t.Celsius())

		// Log tilt readings
		//t.Print()

		select {
		case C <- t:
			// Message sent

		default:
			// No recipients on channel
			err := fmt.Errorf("channel overflow on tilt reading channel")
			hub.CaptureException(err)
			log.Print(err)
		}
	}
}
