package utils

import (
	"strconv"
	"strings"

	"github.com/pkg/errors"
)

func GetMediaDuration(path string) (int64, error) {
	args := []string{
		"-v", "error",
		"-show_entries", "format=duration",
		"-of", "default=noprint_wrappers=1:nokey=1",
		path,
	}

	output, err := ExecCommandOutput("ffprobe", args...)
	if err != nil {
		return 0, errors.Wrap(err, "ffprobe error")
	}

	duration := strings.TrimSpace(string(output))
	durationFloat, err := strconv.ParseFloat(duration, 64)
	if err != nil {
		return 0, errors.Wrap(err, "duration conversion error")
	}

	return int64(durationFloat), nil
}

func CutMedia(input, output string, start, end int64) error {
	args := []string{
		"-y",
		"-hide_banner",
		"-nostats",
		"-v", "error",
		"-ss", strconv.FormatInt(start, 10),
		"-i", input,
		"-t", strconv.FormatInt(end, 10),
		"-c", "copy",
		output,
	}

	return ExecCommand("ffmpeg", args...)
}

// GetFrameImageFromVideo extracts target time frame from a video file and saves it as an image.
func GetFrameImageFromVideo(input, output string, time int64) error {
	args := []string{
		"-y",
		"-hide_banner",
		"-nostats",
		"-v", "error",
		"-i", input,
		"-ss", strconv.FormatInt(time, 10),
		"-vframes", "1",
		output,
	}

	return ExecCommand("ffmpeg", args...)
}
