package main

import (
	"encoding/base32"
	"io"
	"io/fs"
	"log"
	"strings"

	"github.com/cespare/xxhash"
	dlshtml "novit.tech/direktil/local-server/html"
)

func computeUIHash() {
	xxh := xxhash.New()

	err := fs.WalkDir(dlshtml.FS, "ui", func(path string, entry fs.DirEntry, walkErr error) (err error) {
		if walkErr != nil {
			err = walkErr
			return
		}

		if entry.IsDir() {
			return
		}

		f, err := dlshtml.FS.Open(path)
		if err != nil {
			return
		}
		defer f.Close()

		io.Copy(xxh, f)

		return nil
	})

	if err != nil {
		log.Fatal("failed to hash UI: ", err)
	}

	h := strings.ToLower(base32.HexEncoding.WithPadding(base32.NoPadding).EncodeToString(xxh.Sum(nil)))[:5]
	log.Printf("UI hash: %s", h)
	wPublicState.Change(func(v *PublicState) { v.UIHash = h })
}
