package video_old

import (
	"bufio"
	"context"
	"go.uber.org/zap"
	"io"
	"os"
	"os/exec"
	"sync"
)

func Play(ctx context.Context, file string) error {
	if file == "" {
		zap.S().Infoln("video file is empty")
		return nil
	}
	// 判断文件是否存在
	if _, err := os.Stat(file); err != nil {
		zap.S().Errorf("视频文件不存在: %v", err)
		return err
	}
	cmd := exec.CommandContext(ctx, "ffplay", "-autoexit", "-fs", file)
	pipe, err := cmd.StderrPipe()
	if err != nil {
		return err
	}

	var wait sync.WaitGroup
	defer wait.Wait()

	wait.Add(1)
	go func() {
		defer wait.Done()
		reader := bufio.NewReader(pipe)
		for {
			select {
			case <-ctx.Done():
				return
			default:
				line, _, err := reader.ReadLine()
				if err != nil {
					if err == io.EOF {
						return
					}
					break
				}
				zap.L().Info(string(line))
			}
		}
	}()
	return cmd.Run()
}
