package uv

// DefaultTabInterval is the default tab interval.
const DefaultTabInterval = 8

// TabStops represents horizontal line tab stops.
type TabStops struct {
	stops    []int
	interval int
	width    int
}

// NewTabStops creates a new set of tab stops from a number of columns and an
// interval.
func (,  int) *TabStops {
	 := new(TabStops)
	.interval = 
	.width = 
	.stops = make([]int, (+(-1))/)
	.init(0, )
	return 
}

// DefaultTabStops creates a new set of tab stops with the default interval.
func ( int) *TabStops {
	return NewTabStops(, DefaultTabInterval)
}

// Resize resizes the tab stops to the given width.
func ( *TabStops) ( int) {
	if  == .width {
		return
	}

	if  < .width {
		 := ( + (.interval - 1)) / .interval
		.stops = .stops[:]
	} else {
		 := ( - .width + (.interval - 1)) / .interval
		.stops = append(.stops, make([]int, )...)
	}

	.init(.width, )
	.width = 
}

// Width returns the width of the screen that the tab stops are set for.
func ( *TabStops) () int {
	return .width
}

// IsStop returns true if the given column is a tab stop.
func ( TabStops) ( int) bool {
	 := .mask()
	 :=  >> 3
	if  < 0 ||  >= len(.stops) {
		return false
	}
	return .stops[]& != 0
}

// Next returns the next tab stop after the given column.
func ( TabStops) ( int) int {
	return .Find(, 1)
}

// Prev returns the previous tab stop before the given column.
func ( TabStops) ( int) int {
	return .Find(, -1)
}

// Find returns the prev/next tab stop before/after the given column and delta.
// If delta is positive, it returns the next tab stop after the given column.
// If delta is negative, it returns the previous tab stop before the given column.
// If delta is zero, it returns the given column.
func ( TabStops) (,  int) int {
	if  == 0 {
		return 
	}

	var  bool
	 := 
	if  < 0 {
		 = -
		 = true
	}

	for  > 0 {
		if ! {
			if  >= .width-1 {
				return 
			}

			++
		} else {
			if  < 1 {
				return 
			}

			--
		}

		if .IsStop() {
			--
		}
	}

	return 
}

// Set adds a tab stop at the given column.
func ( *TabStops) ( int) {
	 := .mask()
	.stops[>>3] |= 
}

// Reset removes the tab stop at the given column.
func ( *TabStops) ( int) {
	 := .mask()
	.stops[>>3] &= ^
}

// Clear removes all tab stops.
func ( *TabStops) () {
	.stops = make([]int, len(.stops))
}

// mask returns the mask for the given column.
func ( *TabStops) ( int) int {
	return 1 << ( & (.interval - 1))
}

// init initializes the tab stops starting from col until width.
func ( *TabStops) (,  int) {
	for  := ;  < ; ++ {
		if %.interval == 0 {
			.Set()
		} else {
			.Reset()
		}
	}
}