package mark2web

import (
	"path"
	"regexp"
	"strings"

	"gitbase.de/apairon/mark2web/pkg/logger"
	cpy "github.com/otiai10/copy"
)

// ProcessAssets copies the assets from input to output dir
func ProcessAssets() {
	switch Config.Assets.Action {
	case "copy":
		from := Config.Assets.FromPath
		to := Config.Assets.ToPath
		if !strings.HasPrefix(from, "/") {
			from = Config.Directories.Input + "/" + from
		}
		if !strings.HasPrefix(to, "/") {
			to = Config.Directories.Output + "/" + to
		}
		logger.N("copying assets from '%s' to '%s'", from, to)
		err := cpy.Copy(from, to)

		logger.Perr(err, "could not copy assets from '%s' to '%s'", from, to)

		if Config.Assets.Compress {
			compressFilesInDir(to)
		}
	}
}

// fixAssetsPath replaces assets path based on current path
func (node *TreeNode) fixAssetsPath(str string) string {
	if find := Config.Assets.FixTemplate.Find; find != "" {
		logger.D("fixing assets paths for path '%s'", node.CurrentNavPath())
		repl := Config.Assets.FixTemplate.Replace
		toPath := Config.Assets.ToPath

		bToRoot := node.BackToRootPath()
		regex, err := regexp.Compile(find)
		logger.Eexit(err, "could not compile regexp '%s' for assets path", find)

		repl = bToRoot + toPath + "/" + repl
		repl = path.Clean(repl) + "/"
		logger.D("new assets paths: %s", repl)
		return regex.ReplaceAllString(str, repl)
	}

	return str
}
