package tcsh

import (
	
	
	

	
)

var sanitizer = strings.NewReplacer(
	"\n", ``,
	"\r", ``,
	"\t", ``,
)

var quoter = strings.NewReplacer(
	`&`, `\&`,
	`<`, `\<`,
	`>`, `\>`,
	"`", "\\`",
	`'`, `\'`,
	`"`, `\"`,
	`{`, ``, // TODO seems escaping is not working
	`}`, ``, // TODO seems escaping is not working
	`$`, `\$`,
	`#`, `\#`,
	`|`, `\|`,
	`?`, `\?`,
	`(`, `\(`,
	`)`, `\)`,
	`;`, `\;`,
	` `, `\ `,
	`[`, `\[`,
	`]`, `\]`,
	`*`, `\*`,
	`\`, `\\`,
)

func commonPrefix(,  string) string {
	 := 0
	for  < len() &&  < len() && [] == [] {
		++
	}
	return [0:]
}

func commonDisplayPrefix( ...common.RawValue) ( string) {
	for ,  := range  {
		if  == 0 {
			 = .Display
		} else {
			 = commonPrefix(, .Display)
		}
	}
	return
}

func commonValuePrefix( ...common.RawValue) ( string) {
	for ,  := range  {
		if  == 0 {
			 = .Value
		} else {
			 = commonPrefix(, .Value)
		}
	}
	return
}

// ActionRawValues formats values for bash.
func ( string,  common.Meta,  common.RawValues) string {
	 :=  // last segment of currentWord split by COMP_WORDBREAKS

	for ,  := range  {
		// TODO optimize
		if ,  := os.LookupEnv("COMP_WORDBREAKS");  {
			 = strings.Replace(, " ", "", -1)
			if  := strings.LastIndexAny(, );  != -1 {
				.Value = strings.TrimPrefix(.Value, [:+1])
				 = [+1:]
			}
		}
	}

	if len() > 1 && commonDisplayPrefix(...) != "" {
		// When all display values have the same prefix bash will insert is as partial completion (which skips prefixes/formatting).
		if  := commonValuePrefix(...);  !=  {
			// replace values with common value prefix (`\001` is removed in snippet and compopt nospace will be set)
			 = common.RawValuesFrom(commonValuePrefix(...)) // TODO nospaceIndicator
			//values = common.RawValuesFrom(commonValuePrefix(values...) + nospaceIndicator)
		} else {
			// prevent insertion of partial display values by prefixing one with space
			[0].Display = " " + [0].Display
		}
	}

	 := make([]string, len())
	for ,  := range  {
		if len() == 1 {
			[] = quoter.Replace(sanitizer.Replace(.Value))
		} else {
			if .Description != "" {
				// TODO seems actual value needs to be used or it won't be shown if the prefix doesn't match
				[] = fmt.Sprintf("%v_(%v)", quoter.Replace(sanitizer.Replace(.Value)), quoter.Replace(strings.Replace(sanitizer.Replace(.TrimmedDescription()), " ", "_", -1)))
			} else {
				[] = quoter.Replace(sanitizer.Replace(.Value))
			}
		}
	}
	return strings.Join(, "\n")
}