package webserver

import (
	"git.ctdo.de/henne/blitzer-v2/db"
	"git.ctdo.de/henne/blitzer-v2/radar"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

func HandleSetup(ctx *gin.Context) {
	cfg := db.GetConfig()
	err := templates.ExecuteTemplate(ctx.Writer, "setup", gin.H{"Config": cfg})
	if err != nil {
		logrus.Error(err)
	}
}

func HandleSetupSave(ctx *gin.Context) {
	var form SetupForm
	if err := ctx.ShouldBind(&form); err != nil {
		ctx.String(400, "bad input")
		return
	}
	cfg := db.GetConfig()
	cfg.RadarAngle = form.RadarAngle
	cfg.RadarHeight = form.RadarHeight
	cfg.RadarMaxDistance = form.RadarMaxDistance
	cfg.RadarMinDistance = form.RadarMinDistance
	cfg.RadarMaxSpeed = form.RadarMaxSpeed
	cfg.RadarMinSpeed = form.RadarMinSpeed
	cfg.RadarWaveform = form.RadarWaveform
	cfg.TriggerDistance = form.TriggerDistance
	cfg.TriggerSpeed = form.TriggerSpeed

	db.SetConfig(*cfg)
	err := templates.ExecuteTemplate(ctx.Writer, "setup", gin.H{"Config": cfg, "Msg": "Einstellungen wurden gespeichert", "MsgType": "success"})
	if err != nil {
		logrus.Error(err)
	}
	radar.SetConfig(cfg.RadarHeight, cfg.RadarAngle)
}
