package main

import (
	"context"
	"flag"
	"net/http"
	"os"
	"os/signal"
	"time"

	"github.com/simonvetter/modbus"
	"k8s.io/klog"
)

var (
	flagFake                             bool
	flagListenHTTP                       string
	flagPressureThresholdRough           = ScientificNotationValue(1e-1)
	flagPressureThresholdRoughHysteresis = ScientificNotationValue(3e-2)
	flagPressureThresholdHigh            = ScientificNotationValue(1e-4)
	flagPressureThresholdHighHysteresis  = ScientificNotationValue(2e-5)
)

func main() {
	flag.BoolVar(&flagFake, "fake", false, "Enable fake mode which allows to run succd for tests outside the succbone")
	flag.StringVar(&flagListenHTTP, "listen_http", ":8080", "Address at which to listen for HTTP requests")
	flag.TextVar(&flagPressureThresholdRough, "pressure_threshold_rough", &flagPressureThresholdRough, "Threshold for opening up diffusion pump (mbar)")
	flag.TextVar(&flagPressureThresholdRoughHysteresis, "pressure_threshold_rough_hysteresis", &flagPressureThresholdRoughHysteresis, "+-Hysteresis for rough threshold (mbar)")
	flag.TextVar(&flagPressureThresholdHigh, "pressure_threshold_high", &flagPressureThresholdHigh, "Threshold for enabling high voltage circuits (mbar)")
	flag.TextVar(&flagPressureThresholdHighHysteresis, "pressure_threshold_high_hysteresis", &flagPressureThresholdHighHysteresis, "+-Hysteresis for high threshold (mbar)")
	flag.Parse()

	ctx, _ := signal.NotifyContext(context.Background(), os.Interrupt)

	d := daemon{}
	d.daemonState.rpOn = true
	d.daemonState.piraniVolts3.limit = 3
	d.daemonState.piraniVolts100.limit = 100

	d.tempDPBottom = 420.6
	d.tempDPTop = 69.0
	d.tempDPInlet = 42.0
	d.tempSEM = 42.5
	d.humiditySEM = 66.6

	d.aboveRough.threshold = float64(flagPressureThresholdRough)
	d.aboveRough.hysteresis = float64(flagPressureThresholdRoughHysteresis)
	d.aboveHigh.threshold = float64(flagPressureThresholdHigh)
	d.aboveHigh.hysteresis = float64(flagPressureThresholdHighHysteresis)
	if flagFake {
		klog.Infof("Starting with fake peripherals")
		d.adcPirani = &fakeADC{}
	} else {
		adc, err := newBBADC(0)
		if err != nil {
			klog.Exitf("Failed to setup Pirani ADC: %v", err)
		}
		d.adcPirani = adc

		// Setup modbus client
		d.modbusClient, err = modbus.NewClient(&modbus.ClientConfiguration{
			URL:     "tcp://10.250.241.20:8887",
			Timeout: 1 * time.Second,
		})
		if err != nil {
			klog.Exitf("Failed to setup modbus client %v", err)
		}

		// Connect to modbus client
		err = d.modbusClient.Open()
		if err != nil {
			klog.Warningf("Failed to connect to modbus TCP %v", err)
		}
	}

	web := webServer{
		d: &d,
	}
	web.setupViews()

	klog.Infof("Listening for HTTP at %s", flagListenHTTP)
	go func() {
		if err := http.ListenAndServe(flagListenHTTP, nil); err != nil {
			klog.Errorf("HTTP listen failed: %v", err)
		}
	}()

	go d.process(ctx)
	if !flagFake {
		go d.modbusProcess(ctx)
	}

	<-ctx.Done()
}
