package hub

import (
	"embed"
	"html/template"
	"net/http"
	"path/filepath"
	"vppn/hub/api"

	"git.crumpington.com/lib/go/webutil"
)

//go:embed static
var staticFS embed.FS

//go:embed templates
var templateFS embed.FS

type Config struct {
	RootDir    string
	ListenAddr string
	Insecure   bool
}

type App struct {
	api      *api.API
	mux      *http.ServeMux
	tmpl     map[string]*template.Template
	insecure bool
}

func NewApp(conf Config) (*App, error) {
	api, err := api.New(filepath.Join(conf.RootDir, "db.sqlite3"))
	if err != nil {
		return nil, err
	}

	app := &App{
		api:      api,
		mux:      http.NewServeMux(),
		tmpl:     webutil.ParseTemplateSet(templateFuncs, templateFS),
		insecure: conf.Insecure,
	}

	app.registerRoutes()

	return app, nil
}

var templateFuncs = template.FuncMap{
	"ipToString": ipBytesTostring,
}
