package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"strings"

	"github.com/asticode/go-astisub"
	ffmpeg "github.com/u2takey/ffmpeg-go"
	"go.uber.org/multierr"

	"srs.epita.fr/fic-server/admin/sync"
)

func CheckGrammarSubtitleTrack(path string, index uint, lang string, exceptions *sync.CheckExceptions) (errs error) {
	tmpfile, err := ioutil.TempFile("", "resolution-*.srt")
	if err != nil {
		errs = multierr.Append(errs, fmt.Errorf("unable to create a temporary file: %w", err))
		return
	}
	defer os.Remove(tmpfile.Name())

	// Extract subtitles
	err = ffmpeg.Input(path).
		Output(tmpfile.Name(), ffmpeg.KwArgs{"map": fmt.Sprintf("0:%d", index)}).
		OverWriteOutput().Run()
	if err != nil {
		errs = multierr.Append(errs, fmt.Errorf("ffmpeg returns an error when extracting subtitles track: %w", err))
	}

	subtitles, err := astisub.OpenFile(tmpfile.Name())
	if err != nil {
		log.Println("Unable to open subtitles file:", err)
		return
	}

	var lines []string
	for _, item := range subtitles.Items {
		lines = append(lines, item.String())
	}
	for _, e := range multierr.Errors(hooks.CallCustomHook("CheckGrammar", struct {
		Str      string
		Language string
	}{Str: strings.Join(lines, "\n"), Language: lang[:2]}, exceptions)) {
		errs = multierr.Append(errs, fmt.Errorf("subtitle-track: %w", e))
	}

	return
}
