package config

import (
	"git.insit.tech/sas/rtsp_proxy/protos"
	"gopkg.in/yaml.v3"
	"log"
	"os"
	"strings"
	"time"
)

// ParseCamerasYAML parses camera links from YAML file into struct Cameras.
func ParseCamerasYAML(dir string) (map[string]string, error) {
	var CamerasYAML map[string]string

	data, err := os.ReadFile(dir + "/rtsp_reader-writer/writer/internal/config/source.yaml")
	if err != nil {
		return CamerasYAML, err
	}

	err = yaml.Unmarshal(data, &CamerasYAML)
	if err != nil {
		return CamerasYAML, err
	}

	return CamerasYAML, nil
}

// CutURI returns the last part of the URI after "/".
func CutURI(URI string) (CutterURI string) {
	splitted := strings.Split(URI, "/")
	return splitted[len(splitted)-1]
}

// CreateFileName creates FileName structure.
func CreateFileName(dir string, resolutions []string, URI string, period int) *protos.FileName {
	fn := protos.FileName{
		Path:     dir + "/data/" + URI + "/" + resolutions[0],
		TimeNow:  time.Now().Format("15-04-05_02-01-2006"),
		Name:     "videoFragment",
		Number:   -1,
		Duration: float64(period * 60),
	}

	return &fn
}

// Waiter waits for the next period.
func Waiter(period int) {
	periodTD := time.Duration(period) * time.Minute

	now := time.Now()
	nextSegment := now.Truncate(periodTD).Add(periodTD)
	waitDuration := nextSegment.Sub(now)
	log.Printf("waiting for start recording: %v\n", waitDuration)
	time.Sleep(waitDuration)
}
