package layout

import (
	"fmt"
	"os"
	"strings"

	"git.clearsky.net.au/cody/gex.git/pkg/gen/domquery"
)

func ProcessHTML(htmlStr string) (string, error) {
	dom := domquery.LoadHTML(htmlStr)
	layoutTag := dom.QuerySelector("layout")

	if layoutTag.TagName() == "" {
		return dom.OuterHTML(), nil
	}

	attr := layoutTag.GetAttribute("src")

	attr = strings.TrimPrefix(attr, "/")

	attr = strings.Replace(attr, ".tpl", ".gen.tpl", 1)

	layoutFileByt, err := os.ReadFile(attr)
	if err != nil {
		fmt.Printf("ERROR: %s", err)
		return "", err
	}

	// get the block values
	blocks := layoutTag.QuerySelectorAll("block")

	layoutFileHtml := string(layoutFileByt)
	layoutFileHtml, err = ProcessHTML(layoutFileHtml)
	if err != nil {
		fmt.Printf("ERROR: %s\n", err)
	}

	layoutFileDom := domquery.LoadHTML(layoutFileHtml)

	layoutFileBlocks := layoutFileDom.QuerySelectorAll("block")

	for _, block := range blocks {
		for _, layoutFileBlock := range layoutFileBlocks {
			if block.GetAttribute("id") == layoutFileBlock.GetAttribute("id") {
				layoutFileBlock.SetInnerHTML(block.InnerHTML())
			}
		}
	}

	layoutTag.SetOuterHTML(layoutFileDom.InnerHTML())
	htmlStr = dom.InnerHTML()
	//fmt.Println(htmlStr + "\n---------------------------")
	return htmlStr, nil
}
