package ytdl

import (
	"bytes"
	"encoding/json"
	"os/exec"

	"go.fifitido.net/ytdl-web/pkg/ytdl/metadata"
)

func Exec(binary, url string, options ...Option) error {
	opts := Options{
		args:   []string{url},
		stdin:  nil,
		stdout: nil,
		stderr: nil,
		output: nil,
	}
	for _, opt := range options {
		if err := opt(&opts); err != nil {
			return err
		}
	}

	cmd := exec.Command(binary, opts.args...)

	if opts.stdin != nil {
		cmd.Stdin = opts.stdin
	}

	if opts.stdout != nil {
		cmd.Stdout = opts.stdout
	}

	if opts.stderr != nil {
		cmd.Stderr = opts.stderr
	}

	if err := cmd.Run(); err != nil {
		return err
	}

	buf, bufOk := opts.stdout.(*bytes.Buffer)
	meta, metaOk := opts.output.(*metadata.Metadata)
	if bufOk && metaOk {
		if err := json.Unmarshal(buf.Bytes(), meta); err != nil {
			return err
		}
	}

	return nil
}
