package ccolor

import (
	
	
	

	
)

// ColorsToCode convert colors to code. return like "32;45;3"
func ( ...Color) string {
	if len() == 0 {
		return ""
	}

	var  []string
	for ,  := range  {
		 = append(, .String())
	}

	return strings.Join(, ";")
}

func shouldCleanColor() bool {
	return termenv.NoColor() || !termenv.IsSupportColor()
}

/*************************************************************
 * render color code
 *************************************************************/

// RenderCode render message by color code.
//
// Usage:
//
//	msg := RenderCode("3;32;45", "some", "message")
func ( string,  ...any) string {
	var  string
	if  := len();  == 0 {
		return ""
	}

	 = fmt.Sprint(...)
	if len() == 0 {
		return 
	}

	// disabled OR not support color
	if shouldCleanColor() {
		return ClearCode()
	}

	// return fmt.Sprintf(FullColorTpl, code, message)
	return StartSet +  + "m" +  + ResetSet
}

// RenderString render a string with color code.
//
// Usage:
//
//	msg := RenderString("3;32;45", "a message")
func ( string,  string) string {
	if len() == 0 ||  == "" {
		return 
	}

	// disabled OR not support color
	if shouldCleanColor() {
		return ClearCode()
	}

	// return fmt.Sprintf(FullColorTpl, code, str)
	return StartSet +  + "m" +  + ResetSet
}

// RenderWithSpaces Render code with spaces.
// If the number of args is > 1, a space will be added between the args
func ( string,  ...any) string {
	 := formatLikePrintln()
	if len() == 0 {
		return 
	}

	// disabled OR not support color
	if shouldCleanColor() {
		return ClearCode()
	}
	return StartSet +  + "m" +  + ResetSet
}

// ClearCode clear color codes.
//
// eg:
//
//	"\033[36;1mText\x1b[0m" -> "Text"
func ( string) string {
	if !strings.Contains(, CodeSuffix) {
		return 
	}
	return codeRegex.ReplaceAllString(, "")
}

/*************************************************************
 * helper methods for print
 *************************************************************/

// new implementation, support render full color code on pwsh.exe, cmd.exe
func doPrint(,  string) {
	_, lastErr = fmt.Fprint(output, RenderString(, ))
}

func doPrintTo( io.Writer, ,  string) {
	_, lastErr = fmt.Fprint(, RenderString(, ))
}

// new implementation, support render full color code on pwsh.exe, cmd.exe
func doPrintln( string,  []any) {
	doPrintlnTo(output, , )
}

// new implementation, support render full color code on pwsh.exe, cmd.exe
func doPrintlnTo( io.Writer,  string,  []any) {
	_, lastErr = fmt.Fprintln(, RenderString(, formatLikePrintln()))
}

// use Println, will add spaces for each arg
func formatLikePrintln( []any) ( string) {
	if  := len();  == 0 {
		 = ""
	} else if  == 1 {
		 = fmt.Sprint([0])
	} else {
		 = fmt.Sprintln(...)
		// clear last "\n"
		 = [:len()-1]
	}
	return
}