package mark2web

import (
	"path"
	"strings"
)

// ResolveNavPath fixes nav target relative to current navigation path
func (node *TreeNode) ResolveNavPath(target string) string {
	if strings.HasPrefix(target, "/") {
		target = node.BackToRootPath() + target
	}
	target = path.Clean(target)
	return target
}

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

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

// CurrentNavPath is current navigation path for this node
func (node *TreeNode) CurrentNavPath() string {
	curNavPath := strings.TrimPrefix(node.OutputPath, Config.Directories.Output)
	curNavPath = strings.TrimPrefix(curNavPath, "/")
	curNavPath = path.Clean(curNavPath)
	if curNavPath == "." {
		curNavPath = ""
	}

	return curNavPath
}

// BackToRootPath builds ../../ string
func (node *TreeNode) BackToRootPath() string {
	curNavPath := node.CurrentNavPath()

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