package app

import (
	"embed"
	"encoding/json"
	"html/template"
	"net/url"

	"github.com/htfy96/reformism"
	"go.fifitido.net/ytdl-web/pkg/view/html"
	"go.fifitido.net/ytdl-web/pkg/ytdl/metadata"
)

//go:embed views/*
var viewsfs embed.FS

var Views = html.New(
	viewsfs,
	html.DefaultOptions().
		WithBaseDir("views").
		WithFunction("unsafe", func(s string) template.HTML {
			return template.HTML(s)
		}).
		WithFunction("queryEscape", func(s string) string {
			return url.QueryEscape(s)
		}).
		WithFunction("jsonMarshal", func(s any) (string, error) {
			j, err := json.MarshalIndent(s, "", "    ")
			if err != nil {
				return "", err
			}
			return string(j), nil
		}).
		WithFunction("downloadContext", func(meta metadata.Metadata, url, basePath string, format metadata.Format) map[string]any {
			return map[string]any{
				"Meta":     meta,
				"Url":      url,
				"BasePath": basePath,
				"Format":   format,
			}
		}).
		WithFunctions(reformism.FuncsHTML),
)

func init() {
	if err := Views.Load(); err != nil {
		panic(err)
	}
}
