package gutil

type Ring[T any] struct {
	next, prev *Ring[T]
	Value      T // for use by client; untouched by this library
}

// NewRing creates a ring of n elements
func NewRing[T any](n int) *Ring[T] {
	if n <= 0 {
		return nil
	}
	r := new(Ring[T])
	p := r
	for i := 1; i < n; i++ {
		p.next = &Ring[T]{prev: p}
		p = p.next
	}
	p.next = r
	r.prev = p

	return r
}

// Len computes the number of elements in ring r.
// It executes in time proportional to the number of elements.
func (r *Ring[T]) Len() int {
	n := 0
	if r == nil {
		return n
	}
	n = 1
	for p := r.next; p != r; p = p.next {
		n++
	}
	return n
}

// Next returns the next ring element. r must not be empty.
func (r *Ring[T]) Next() *Ring[T] {
	if r == nil {
		return r.init()
	}
	return r.next
}
func (r *Ring[T]) init() *Ring[T] {
	r.next = r
	r.prev = r
	return r
}

func (r *Ring[T]) Do(fn func(t T)) {
	if r == nil {
		return
	}
	// 第一个
	fn(r.Value)
	// 其他
	for p := r.next; p != r; p = p.next {
		fn(p.Value)
	}
}

// Move moves n % r.Len() elements backward (n < 0) or forward (n >= 0)
// in the ring and returns that ring element. r must not be empty.
func (r *Ring[T]) Move(n int) *Ring[T] {
	if r.next == nil {
		return r.init()
	}
	switch {
	case n < 0:
		for ; n < 0; n++ {
			r = r.prev
		}
	case n > 0:
		for ; n > 0; n-- {
			r = r.next
		}
	}
	return r
}

// Link connects ring r with ring s such that r.Next()
// becomes s and returns the original value for r.Next().
// r must not be empty.
//
// If r and s point to the same ring, linking
// them removes the elements between r and s from the ring.
// The removed elements form a subring and the result is a
// reference to that subring (if no elements were removed,
// the result is still the original value for r.Next(),
// and not nil).
//
// If r and s point to different rings, linking
// them creates a single ring with the elements of s inserted
// after r. The result points to the element following the
// last element of s after insertion.
func (r *Ring[T]) Link(s *Ring[T]) *Ring[T] {
	n := r.Next()
	if s != nil {
		p := s.Prev()
		// Note: Cannot use multiple assignment because
		// evaluation order of LHS is not specified.
		r.next = s
		s.prev = r
		n.prev = p
		p.next = n
	}
	return n
}

// Prev returns the previous ring element. r must not be empty.
func (r *Ring[T]) Prev() *Ring[T] {
	if r.next == nil {
		return r.init()
	}
	return r.prev
}

// Unlink removes n % r.Len() elements from the ring r, starting
// at r.Next(). If n % r.Len() == 0, r remains unchanged.
// The result is the removed subring. r must not be empty.
func (r *Ring[T]) Unlink(n int) *Ring[T] {
	if n <= 0 {
		return nil
	}
	return r.Link(r.Move(n + 1))
}
