package img

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

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

func Process(htmlDir string, tag *domquery.Node) string {

	imgSrc := tag.GetAttribute("src")
	fileName := filepath.Base(imgSrc)

	if !strings.Contains(imgSrc, "app/") {
		imgSrc = htmlDir + "/" + imgSrc
	}

	imgSrc = strings.Replace(imgSrc, "/app/", "app/", 1)
	_, err := os.ReadFile(imgSrc)
	if err != nil {
		fmt.Println(err)
		return ""
	}

	w := tag.GetAttribute("w")
	h := tag.GetAttribute("h")

	cx := tag.GetAttribute("cx")
	if cx == "" {
		cx = "0"
	}

	cy := tag.GetAttribute("cy")
	if cy == "" {
		cy = "0"
	}

	cw := tag.GetAttribute("cw")
	if cw == "" {
		cw = "0"
	}

	ch := tag.GetAttribute("ch")
	if ch == "" {
		ch = "0"
	}

	q := tag.GetAttribute("q")

	command := "convert " + imgSrc + " -auto-orient"
	if w != "" || h != "" {
		command += " -resize " + w + "x" + h
	}

	if cw != "" && ch != "" {
		command += " -crop " + cw + "x" + ch + "+" + cx + "+" + cy
	}

	if q != "" {
		command += " -quality " + q
	}

	newImgSrc := "app/pub/gen/" + strings.Split(fileName, ".")[0] + w + h + cx + cy + cw + ch + q + ".webp"
	_, err = os.ReadFile(newImgSrc)
	if err == nil {
		tag.SetAttribute("src", "/"+newImgSrc)
		return ""
	} else {
		fmt.Println(err)
	}

	command += " " + newImgSrc

	cmd := exec.Command("bash", "-c", command)
	_, err = cmd.Output()

	if err != nil {
		fmt.Println(err)
	}

	tag.SetAttribute("src", "/"+newImgSrc)
	tag.RemoveAttribute("webp")
	tag.RemoveAttribute("w")
	tag.RemoveAttribute("h")
	tag.RemoveAttribute("cx")
	tag.RemoveAttribute("cy")
	tag.RemoveAttribute("cw")
	tag.RemoveAttribute("ch")

	return ""
}
