package helper

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

	"gitbase.de/apairon/mark2web/config"
	"github.com/flosch/pongo2"
)

var templateCache = make(map[string]*pongo2.Template)
var currentContext *map[string]interface{}
var currentTreeNodeConfig *config.PathConfigTree
var currentPathConfig *config.PathConfig
var templateDir string

// BackToRoot builds ../../ string
func BackToRoot(curNavPath string) string {
	tmpPath := ""
	if curNavPath != "" {
		for i := strings.Count(curNavPath, "/") + 1; i > 0; i-- {
			tmpPath += "../"
		}
	}
	return tmpPath
}

// ResolveNavPath fixes nav target relative to current navigation path
func ResolveNavPath(target string) string {
	curNavPath := (*currentContext)["CurrentPath"].(string)
	if strings.HasPrefix(target, "/") {
		target = BackToRoot(curNavPath) + target
	}
	target = path.Clean(target)
	return target
}

// ResolveOutputPath fixes output directory relative to current navigation path
func ResolveOutputPath(target string) string {
	if strings.HasPrefix(target, "/") {
		target = config.Config.Directories.Output + "/" + target
	} else {
		target = currentTreeNodeConfig.OutputPath + "/" + target
	}
	return path.Clean(target)
}

// ResolveInputPath fixes input directory relative to current navigation path
func ResolveInputPath(target string) string {
	if strings.HasPrefix(target, "/") {
		target = config.Config.Directories.Input + "/" + target
	} else {
		target = currentTreeNodeConfig.InputPath + "/" + target
	}
	return path.Clean(target)
}

// SetTemplateDir sets base directory for searching template files
func SetTemplateDir(dir string) {
	templateDir = dir
}

// RenderTemplate renders a pongo2 template with context
func RenderTemplate(filename string, treeNodeConfig *config.PathConfigTree, pathConfig *config.PathConfig, ctx *map[string]interface{}) (string, error) {
	currentContext = ctx
	currentTreeNodeConfig = treeNodeConfig
	currentPathConfig = pathConfig
	templateFile := templateDir + "/" + filename
	template := templateCache[templateFile]
	if template == nil {
		var err error
		if template, err = pongo2.FromFile(templateFile); err != nil {
			log.Panicf("could not parse template '%s': %s", templateFile, err)
		} else {
			templateCache[templateFile] = template
		}
	}

	return template.Execute(*ctx)
}

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

		bToRoot := 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) + "/"
		Log.Debugf("new assets paths: %s", repl)
		return regex.ReplaceAllString(str, repl)
	}

	return str
}
