package main

import (
	"fmt"
	"git.entr0py.de/garionion/pac3100-exporter/exporter"
	"git.entr0py.de/garionion/pac3100-exporter/scraper"
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
	"os"
	"sync"
	"time"
)

func main() {
	zerolog.TimeFieldFormat = time.RFC1123Z
	consoleWriter := zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC1123Z}
	log.Logger = log.Output(consoleWriter).With().Timestamp().Logger()

	exp := exporter.New()

	usb0, err := scraper.New("/dev/ttyUSB0", log.Logger)
	if err != nil {
		log.Panic().Err(err)
	}

	usb1, err := scraper.New("/dev/ttyUSB1", log.Logger)
	if err != nil {
		log.Panic().Err(err)
	}

	log.Info().Msg("starting")
	go scrape(exp, usb0, usb1)

	app := echo.New()
	app.Use(middleware.Recover())

	app.GET("/metrics", echo.WrapHandler(promhttp.Handler()))

	log.Fatal().Err(app.Start(":9555"))
}

func scrape(exp exporter.Exporter, devices ...*scraper.Scraper) {
	var wg sync.WaitGroup

	ticker := time.NewTicker(1 * time.Second)
	for {
		wg.Add(2)
		go func() {
			defer wg.Done()
			measurement, err := devices[0].GetMeasurments()
			if err != nil {
				fmt.Println(err.Error())
			}
			exp.SetMeasurements(measurement, "device0")
		}()
		go func() {
			defer wg.Done()
			measurement, err := devices[1].GetMeasurments()
			if err != nil {
				fmt.Println(err.Error())
			}
			exp.SetMeasurements(measurement, "device1")
		}()

		wg.Wait()

		<-ticker.C
	}
}
