package radar

import (
	"fmt"

	"git.ctdo.de/henne/blitzer-v2/camera"
	"git.ctdo.de/henne/blitzer-v2/config"
	"git.ctdo.de/henne/blitzer-v2/db"
	"git.ctdo.de/henne/blitzer-v2/printer"
	"git.ctdo.de/henne/blitzer-v2/radar_lib"
	"git.ctdo.de/henne/blitzer-v2/speedsign"
	"github.com/sirupsen/logrus"
)

var r *radar_lib.Radar

func init() {
	r = radar_lib.New(config.C.Radar.Port, config.C.Radar.Baud)
	r.SetEventHandler(onEvent)
	r.SetSpeedHandler(onSpeedEvent)
}

func onSpeedEvent(speed int) {
	speedsign.Show(speed)
}

func onEvent(speed int) {
	speedingTicket := db.SpeedingTicket{
		Speed:        speed,
		AllowedSpeed: db.GetConfig().TriggerSpeed,
	}
	if err := db.DB.Save(&speedingTicket).Error; err != nil {
		logrus.Error(err)
	}
	if err := camera.TakePhoto(speedingTicket.ID.String()); err != nil {
		logrus.Error(err)
	}
	speedingTicket.ImagePath = fmt.Sprintf("/images/original/ticket-%s.jpg", speedingTicket.ID)
	if err := db.DB.Save(&speedingTicket).Error; err != nil {
		logrus.Error(err)
	}
	printer.PrintTicket(speedingTicket)
}

func SetConfig(height int, angle int) {
	r.SetBaseConfig(height, angle, 0)
}

func SetSpeedConfig(speed int, minDistance, maxDistance, minSpeed, maxSpeed, triggerDistance int) {
	r.SetTargetSpeedConfig(radar_lib.DirectionBidirectional, minDistance*2, maxDistance*2, minSpeed, maxSpeed, speed, radar_lib.OutputLogicMostPlausible)
}

func SetBaseConfig() {
	r.SetCommunicationConfig(radar_lib.PortRS485, radar_lib.Baud115200, radar_lib.OutputTypeNoOutput, radar_lib.OutputTypeNoOutput, radar_lib.OutputTypeNoOutput, 50)
}

/*
	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
*/
