package printer

import (
	"image"
	"os"

	"git.ctdo.de/henne/blitzer-v2/config"
	"git.ctdo.de/henne/blitzer-v2/db"
	"github.com/hennedo/escpos"
	"github.com/sirupsen/logrus"
	"go.bug.st/serial"
)

var printer *escpos.Escpos
var whyImage image.Image

func init() {
	if config.C.PrinterPort == "" {
		return
	}
	socket, err := serial.Open(config.C.PrinterPort, &serial.Mode{
		BaudRate: 19200,
		StopBits: serial.OneStopBit,
		DataBits: 8,
		Parity:   serial.NoParity,
	})
	if err != nil {
		logrus.Panicf("printer error serial port: %s", err)
	}
	printer = escpos.New(socket)
	imageFile, err := os.Open("webserver/assets/img/traffic_police.jpg")
	if err != nil {
		logrus.Errorf("error loading image: %s", err)
	}
	whyImage, _, err = image.Decode(imageFile)
	if err != nil {
		logrus.Errorf("image decoding error: %s", err)
	}

}

func PrintTicket(ticket db.SpeedingTicket) {
	if config.C.PrinterPort == "" {
		return
	}
	printer.Initialize()
	printer.PrintImage(whyImage)
}
