package main

import (
	"hash/crc32"
	"path/filepath"
	"regexp"
	"runtime"
	"strconv"
	"strings"

	"github.com/PumpkinSeed/cage"
	"github.com/gohugoio/hugo/commands"
	"github.com/spf13/viper"
)

func hugoContext(hugo *Hugo, gitRepoPath string) {
	viper.SetConfigName("config")
	viper.SetConfigType("toml")
	viper.AddConfigPath(filepath.Join(hugo.SourceDir))
	err := viper.ReadInConfig()
	check(err)
	gitRepoPathChecksum := strconv.FormatUint(uint64(crc32.ChecksumIEEE([]byte(gitRepoPath))), 16)
	reg, err := regexp.Compile("[^a-zA-Z0-9]+")
	check(err)
	hugoTitle := reg.ReplaceAllString(viper.GetString("title"), "")
	hugo.PublicHTMLName = strings.ToLower(hugoTitle) + "-" + gitRepoPathChecksum
	hugo.CatalogName = viper.GetString("params.sandpointsCatalogName")
	hugo.CatalogPrefix = viper.GetString("params.sandpointsCatalogPrefix")
	hugo.DestinationDir = filepath.Join(hugo.SourceDir, "public")
}

func hugoRender(hugo *Hugo, hookOffline bool) string {
	// fmt.Println("hugo", "-s", hugo.SourceDir, "-d", hugo.DestinationDir, "--templateMetrics")
	logs := cage.Start()
	hugoCommand := []string{"-s", hugo.SourceDir, "-d", hugo.DestinationDir, "--templateMetrics"}
	if hookOffline {
		hugoCommand = append(hugoCommand, []string{"-e", "offline"}...)
	}
	goHugo := commands.Execute(hugoCommand)
	cage.Stop(logs)
	if goHugo.Err != nil {
		check(goHugo.Err)
		runtime.Goexit()
	}
	lgs := "~~~~~~~ Hugo's logs ~~~~~~~\n"
	for _, l := range logs.Data {
		lgs = lgs + l + "\n"
	}
	return lgs
}
