package zos

import "strconv"

type FByteView struct {
	Line []byte
	sign byte
	err  error
}

func NewByteView(line []byte) *FByteView {
	return &FByteView{
		Line: line,
		sign: ' ',
		err:  nil,
	}
}
func (v *FByteView) Err() error {
	return v.err
}
func (v *FByteView) SetSign(sign byte) {
	v.sign = sign
}
func (v *FByteView) GetToken() []byte {
	if v.sign == ' ' {
		return v.ReadTokenBySpace()
	}
	return v.ReadTokenByChar(v.sign)
}
func (v *FByteView) GetInt() int32 {
	if v.err != nil {
		return 0
	}
	token := string(v.GetToken())
	num, err := strconv.ParseInt(token, 10, 32)
	v.err = err
	return int32(num)
}
func (v *FByteView) GetFloat() float32 {
	if v.err != nil {
		return 0
	}
	token := string(v.GetToken())
	num, err := strconv.ParseFloat(token, 32)
	v.err = err
	return float32(num)
}

func (v *FByteView) SkipWhitespace() {
	r, w := 0, len(v.Line)
	for r < w && (v.Line[r] == ' ' || v.Line[r] == '\t') {
		r++
	}
	if r > 0 {
		v.Line = v.Line[r:w]
	}
}
func (v *FByteView) ReadTokenBySpace() []byte {
	v.SkipWhitespace()
	r, w := 0, len(v.Line)
	for r < w && (v.Line[r] != ' ' && v.Line[r] != '\t') {
		r++
	}
	token := v.Line[0:r]
	v.Line = v.Line[r:w]
	return token
}
func (v *FByteView) ReadTokenByChar(char byte) []byte {
	v.SkipWhitespace()
	r, w := 0, len(v.Line)
	for r < w && (v.Line[r] != char) {
		r++
	}
	token := v.Line[0:r]
	v.Line = v.Line[r:w]
	return token
}
