package media

import (
	"bytes"
	"fmt"
	"image"
	"os"
	"os/exec"
	"path"
	"path/filepath"
)

func VideoFrame(filename string) (image.Image, error) {
	cmd := exec.Command("ffmpeg", "-i", filename, "-vframes", "1", "-f", "singlejpeg", "-")
	buffer := new(bytes.Buffer)
	cmd.Stdout = buffer
	if cmd.Run() != nil {
		return nil, fmt.Errorf("could not generate frame")
	}

	img, _, err := image.Decode(buffer)
	return img, err
}

func VideoSize(filename string) (image.Rectangle, error) {
	img, err := VideoFrame(filename)
	if err != nil {
		return image.Rectangle{}, err
	}
	return img.Bounds(), nil
}

func VideoEncode(filename string, size image.Rectangle, thumbDir string) error {
	dest := thumbFilename(thumbDir, size, path.Base(filename))
	os.MkdirAll(filepath.Dir(dest), 0755)
	cmd := exec.Command("ffmpeg", "-i", filename, "-vf", fmt.Sprintf("scale=%d:%d", size.Dx(), size.Dy()), "-strict", "-2", dest)
	if out, err := cmd.CombinedOutput(); err != nil {
		os.Remove(dest)
		return fmt.Errorf("could not thumb video: %s", string(out))
	}
	return nil
}
