package thumbnail

import (
	"bytes"
	"image"
	"image/png"
	"io"
	"os/exec"
)

func (this *DirectThumbnailer) videoSnapshot(absPath string) (image.Image, error) {

	cmd := exec.Command(
		"ffmpeg",
		"-loglevel", "0",
		"-timelimit", "10", // seconds
		"-an",
		"-i", absPath,
		"-vf", `thumbnail`,
		"-frames:v", "1",
		"-f", "image2pipe",
		"-c:v", "png", // always PNG output - we will resample/rescale it ourselves
		"-",
	)

	// -ss 00:00:30

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return nil, err
	}

	err = cmd.Start()
	if err != nil {
		return nil, err
	}

	out := bytes.Buffer{}
	_, err = io.Copy(&out, stdout)
	if err != nil {
		return nil, err
	}

	err = cmd.Wait()
	if err != nil {
		return nil, err
	}

	// Try to decode as PNG image

	return png.Decode(bytes.NewReader(out.Bytes()))
}
