package environment

import (
	"os"
	"path"
	"path/filepath"
	"regexp"
	"strings"
)

func ReadTemplate(argPath string) string {

	current, err := os.Getwd()
	if err != nil {
		ExitWithError(2, "The current directory cannot be read")
	}

	p := argPath

	if !filepath.IsAbs(p) {
		p = path.Clean(current + "/" + p)
	}

	template, err := os.ReadFile(p)
	if err != nil {
		ExitWithError(2, "The file %s cannot be read", p)
	}

	return convertTemplateImages(string(template), path.Dir(p))
}

func convertTemplateImages(content string, absolute string) string {
	content = convertTemplateLogo(content, absolute)
	content = convertTemplateLatexLogo(content, absolute)

	return content

}

func convertTemplateLogo(content string, absolute string) string {
	todoRegEx := regexp.MustCompile(`(?m)^(?P<match>logo:\s*"?(?P<path>[^"\n]*)"?\s*)$`)

	matches := todoRegEx.FindAllStringSubmatch(content, -1)
	if matches == nil {
		return content
	}

	for _, match := range matches {
		result := make(map[string]string)
		for i, name := range todoRegEx.SubexpNames() {
			if i != 0 && name != "" {
				result[name] = match[i]
			}
		}

		if filepath.IsAbs(result["path"]) {
			continue
		}

		path := path.Clean(absolute + "/" + result["path"])
		content = strings.Replace(content, result["match"], "logo: \""+path+"\"", -1)

	}

	return content
}

func convertTemplateLatexLogo(content string, absolute string) string {
	todoRegEx := regexp.MustCompile(`(?m)(?P<match>\\includegraphics[^{]*\{(?P<path>[^}]*)\})`)

	matches := todoRegEx.FindAllStringSubmatch(content, -1)
	if matches == nil {
		return content
	}

	for _, match := range matches {
		result := make(map[string]string)
		for i, name := range todoRegEx.SubexpNames() {
			if i != 0 && name != "" {
				result[name] = match[i]
			}
		}

		if filepath.IsAbs(result["path"]) {
			continue
		}

		path := path.Clean(absolute + "/" + result["path"])
		a := strings.Replace(result["match"], result["path"], path, -1)

		content = strings.Replace(content, result["match"], a, -1)

	}

	return content
}

/**

func CreatePDF() error {

	err, pageData := collectStructureFromFiles(config.Path)
	if err != nil {
		return err
	}

	d, err := getDataset(pageData, flagInitChangelog|flagInitTasks|flagInitDocuments)
	if err != nil {
		return err
	}

	outputName := arguments.Build.PDF.Output

	if outputName == "" {
		printErrorAndExit(2, "if the type is pdf, the output option must be specified")
	}

	file, err := ioutil.TempFile(os.TempDir(), "docman")
	if err != nil {
		printErrorAndExit(2, "A temporary file cannot be created", err.Error())
	}
	defer os.Remove(file.Name())

	t, err := template.New("pdf").Parse(config.PDF.Template.Internal.MarkdownContent)
	if err != nil {
		return err
	}

	err = t.Execute(file, d)
	if err != nil {
		return err
	}

	createLuaFile()
	runPandoc(file.Name(), outputName, config.PDF.Template.Latex)

	if luaRawBlockFile != nil {
		luaRawBlockFile.Close()
	}

	return nil

}

var luaRawBlockFile *os.File

func createLuaFile() {
	var err error

	luaRawBlockFile, err = ioutil.TempFile(os.TempDir(), "lua-raw-block")
	if err != nil {
		printErrorAndExit(2, "A temporary file cannot be created", err.Error())
	}

	luaRawBlockFile.WriteString(`
function RawBlock (raw)
	return raw.format:match 'html'
	and pandoc.read(raw.text, 'html').blocks
	or raw
end
`)

}

func getAdjustedContent(absolute string) string {

	content, err := os.ReadFile(absolute)
	if err != nil {
		printError("The file cannot be read", absolute)
		return ""
	}

	err, def := splitYamlParts(content)
	if err != nil {
		printError(err.Error())
		return ""
	}

	s := convertImages(def.text, path.Dir(absolute))

	return s
}

func convertImages(content string, absolute string) string {

	todoRegEx := regexp.MustCompile(`(?P<match>\!\[(?P<label>[^]]*)\]\((?P<path>[^)]*)\))`)

	matches := todoRegEx.FindAllStringSubmatch(content, -1)
	if matches == nil {
		return content
	}

	for _, match := range matches {
		result := make(map[string]string)
		for i, name := range todoRegEx.SubexpNames() {
			if i != 0 && name != "" {
				result[name] = match[i]
			}
		}

		if filepath.IsAbs(result["path"]) {
			continue
		}

		path := path.Clean(absolute + "/" + result["path"])
		content = strings.Replace(content, result["match"], "!["+result["label"]+"]("+path+")", -1)

	}

	return content
}


*/