package vt10x

import (
	
	
	
	
	
)

// STR sequences are similar to CSI sequences, but have string arguments (and
// as far as I can tell, don't really have a name; STR is the name I took from
// suckless which I imagine comes from rxvt or xterm).
type strEscape struct {
	typ  rune
	buf  []rune
	args []string
}

func ( *strEscape) () {
	.typ = 0
	.buf = .buf[:0]
	.args = nil
}

func ( *strEscape) ( rune) {
	// TODO: improve allocs with an array backed slice; bench first
	if len(.buf) < 256 {
		.buf = append(.buf, )
	}
	// Going by st, it is better to remain silent when the STR sequence is not
	// ended so that it is apparent to users something is wrong. The length sanity
	// check ensures we don't absorb the entire stream into memory.
	// TODO: see what rxvt or xterm does
}

func ( *strEscape) () {
	.args = strings.Split(string(.buf), ";")
}

func ( *strEscape) (,  int) int {
	if  >= len(.args) ||  < 0 {
		return 
	}
	,  := strconv.Atoi(.args[])
	if  != nil {
		return 
	}
	return 
}

func ( *strEscape) ( int,  string) string {
	if  >= len(.args) ||  < 0 {
		return 
	}
	return .args[]
}

func ( *State) () {
	 := &.str
	.parse()

	switch .typ {
	case ']': // OSC - operating system command
		var  *string
		switch  := .arg(0, 0);  {
		case 0, 1, 2:
			 := .argString(1, "")
			if  != "" {
				.setTitle()
			}
		case 10:
			if len(.args) < 2 {
				break
			}

			 := .argString(1, "")
			 := &
			if  != nil && * == "?" {
				.oscColorResponse(int(DefaultFG), 10)
			} else if  := .setColorName(int(DefaultFG), );  != nil {
				.logf("invalid foreground color: %s\n", maybe())
			} else {
				// TODO: redraw
			}
		case 11:
			if len(.args) < 2 {
				break
			}

			 := .argString(1, "")
			 := &
			if  != nil && * == "?" {
				.oscColorResponse(int(DefaultBG), 11)
			} else if  := .setColorName(int(DefaultBG), );  != nil {
				.logf("invalid cursor color: %s\n", maybe())
			} else {
				// TODO: redraw
			}
		// case 12:
		// if len(s.args) < 2 {
		// 	break
		// }

		// c := s.argString(1, "")
		// p := &c
		// if p != nil && *p == "?" {
		// 	t.oscColorResponse(int(DefaultCursor), 12)
		// } else if err := t.setColorName(int(DefaultCursor), p); err != nil {
		// 	t.logf("invalid background color: %s\n", p)
		// } else {
		// 	// TODO: redraw
		// }
		case 4: // color set
			if len(.args) < 3 {
				break
			}

			 := .argString(2, "")
			 = &
			fallthrough
		case 104: // color reset
			 := -1
			if len(.args) > 1 {
				 = .arg(1, 0)
			}
			if  != nil && * == "?" { // report
				.osc4ColorResponse()
			} else if  := .setColorName(, );  != nil {
				if !( == 104 && len(.args) <= 1) {
					.logf("invalid color j=%d, p=%s\n", , maybe())
				}
			} else {
				// TODO: redraw
			}
		default:
			.logf("unknown OSC command %d\n", )
			// TODO: s.dump()
		}
	case 'k': // old title set compatibility
		 := .argString(0, "")
		if  != "" {
			.setTitle()
		}
	default:
		// TODO: Ignore these codes instead of complain?
		// 'P': // DSC - device control string
		// '_': // APC - application program command
		// '^': // PM - privacy message

		.logf("unhandled STR sequence '%c'\n", .typ)
		// t.str.dump()
	}
}

func ( *State) ( int,  *string) error {
	if !between(, 0, 1<<24) {
		return fmt.Errorf("invalid color value %d", )
	}

	if  == nil {
		// restore color
		delete(.colorOverride, Color())
	} else {
		// set color
		, , ,  := parseColor(*)
		if  != nil {
			return 
		}
		.colorOverride[Color()] = Color(<<16 | <<8 | )
	}

	return nil
}

func ( *State) (,  int) {
	if  < 0 {
		.logf("failed to fetch osc color %d\n", )
		return
	}

	,  := .colorOverride[Color()]
	if  {
		 = int()
	}

	, ,  := rgb()
	.w.Write([]byte(fmt.Sprintf("\033]%d;rgb:%02x%02x/%02x%02x/%02x%02x\007", , , , , , , )))
}

func ( *State) ( int) {
	if  < 0 {
		.logf("failed to fetch osc4 color %d\n", )
		return
	}

	,  := .colorOverride[Color()]
	if  {
		 = int()
	}

	, ,  := rgb()
	.w.Write([]byte(fmt.Sprintf("\033]4;%d;rgb:%02x%02x/%02x%02x/%02x%02x\007", , , , , , , )))
}

func rgb( int) (, ,  int) {
	return ( >> 16) & 0xff, ( >> 8) & 0xff,  & 0xff
}

var (
	RGBPattern  = regexp.MustCompile(`^([\da-f]{1})\/([\da-f]{1})\/([\da-f]{1})$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$`)
	HashPattern = regexp.MustCompile(`[\da-f]`)
)

func parseColor( string) (, ,  int,  error) {
	if len() == 0 {
		 = fmt.Errorf("empty color spec")
		return
	}

	 := strings.ToLower()
	if strings.HasPrefix(, "rgb:") {
		 = [4:]
		 := RGBPattern.FindAllStringSubmatch(, -1)
		if len() != 1 || len([0]) == 0 {
			 = fmt.Errorf("invalid rgb color spec: %s", )
			return
		}
		 := [0]

		var  float64
		if len([1]) > 0 {
			 = 15
		} else if len([4]) > 0 {
			 = 255
		} else if len([7]) > 0 {
			 = 4095
		} else {
			 = 65535
		}

		,  := strconv.ParseInt(firstNonEmpty([1], [4], [7], [10]), 16, 0)
		if  != nil {
			return , , , 
		}

		,  := strconv.ParseInt(firstNonEmpty([2], [5], [8], [11]), 16, 0)
		if  != nil {
			return , , , 
		}

		,  := strconv.ParseInt(firstNonEmpty([3], [6], [9], [12]), 16, 0)
		if  != nil {
			return , , , 
		}

		 = int(math.Round(float64() /  * 255))
		 = int(math.Round(float64() /  * 255))
		 = int(math.Round(float64() /  * 255))
		return , , , nil
	} else if strings.HasPrefix(, "#") {
		 = [1:]
		 := HashPattern.FindAllString(, -1)
		if !oneOf(len(), []int{3, 6, 9, 12}) {
			 = fmt.Errorf("invalid hash color spec: %s", )
			return
		}

		 := len() / 3
		for  := 0;  < 3; ++ {
			,  := strconv.ParseInt([*:*+], 16, 0)
			if  != nil {
				return , , , 
			}

			var  int64
			switch  {
			case 1:
				 =  << 4
			case 2:
				 = 
			case 3:
				 =  >> 4
			default:
				 =  >> 8
			}

			switch  {
			case 0:
				 = int()
			case 1:
				 = int()
			case 2:
				 = int()
			}
		}
		return
	} else {
		 = fmt.Errorf("invalid color spec: %s", )
		return
	}
}

func maybe( *string) string {
	if  == nil {
		return "<nil>"
	}
	return *
}

func firstNonEmpty( ...string) string {
	if len() == 0 {
		return ""
	}
	for ,  := range  {
		if len() > 0 {
			return 
		}
	}
	return [len()-1]
}

func oneOf( int,  []int) bool {
	for ,  := range  {
		if  ==  {
			return true
		}
	}
	return false
}