package camera

import (
	"fmt"
	"os/exec"

	"github.com/disintegration/imaging"
	"github.com/sirupsen/logrus"
)

var gphotoPath string

func init() {
	var err error
	gphotoPath, err = exec.LookPath("gphoto2")
	if err != nil {
		logrus.Panic("gphoto2 not found")
	}
}

func TakePhoto(id string) error {
	filename := fmt.Sprintf("images/original/ticket-%s.jpg", id)
	cmd := exec.Command(gphotoPath, "--capture-image-and-download", "--filename", filename)
	err := cmd.Run()
	if err != nil {
		return err
	}
	img, err := imaging.Open("./" + filename)
	if err != nil {
		return err
	}
	rotated := imaging.Rotate180(img)
	err = imaging.Save(rotated, filename, imaging.JPEGQuality(95))
	if err != nil {
		return err
	}
	return nil
}
