package mark2web

import (
	"log"
	"path"
	"regexp"
	"strings"

	"gitbase.de/apairon/mark2web/pkg/helper"
	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
		}
		helper.Log.Noticef("copying assets from '%s' to '%s'", from, to)
		err := cpy.Copy(from, to)
		if err != nil {
			helper.Log.Panicf("could not copy assets from '%s' to '%s': %s", from, to, err)
		}
	}
}

// fixAssetsPath replaces assets path based on current path
func fixAssetsPath(str, curNavPath string) string {
	if find := Config.Assets.FixTemplate.Find; find != "" {
		helper.Log.Debugf("fixing assets paths for path '%s'", curNavPath)
		repl := Config.Assets.FixTemplate.Replace
		toPath := Config.Assets.ToPath

		bToRoot := helper.BackToRoot(curNavPath)
		regex, err := regexp.Compile(find)
		if err != nil {
			log.Panicf("could not compile regexp '%s' for assets path: %s", find, err)
		}
		repl = bToRoot + toPath + "/" + repl
		repl = path.Clean(repl) + "/"
		helper.Log.Debugf("new assets paths: %s", repl)
		return regex.ReplaceAllString(str, repl)
	}

	return str
}
