package game

// LineClearAnimation clears completed lines cell-by-cell to create
// a visual wipe effect from the center outward.
//
// Once the lines are cleared, the remaining lines are moved down.
type LineClearAnimation struct {
	// lines to clear.
	lines []byte
	// next index to clear to the left
	leftIndex int8
	// next index to clear to the right
	rightIndex int8
}

func (lca *LineClearAnimation) Reset() {
	lca.lines = []byte{}
}

func (lca LineClearAnimation) NumLines() int {
	return len(lca.lines)
}

func (lca *LineClearAnimation) SetLines(rows []byte) {
	lca.lines = rows

	lca.leftIndex = (GRID_WIDTH - 1) / 2
	if (GRID_WIDTH-1)%2 != 0 {
		lca.rightIndex = lca.leftIndex + 1
	} else {
		lca.rightIndex = lca.leftIndex
	}
}

func (lca *LineClearAnimation) Update(grid *Grid) {
	if lca.Completed() {
		return
	}

	if lca.leftIndex < 0 || lca.rightIndex > GRID_WIDTH {
		grid.MoveLinesDown(lca.lines...)
		lca.Reset()
		return
	}

	for _, lineIndex := range lca.lines {
		grid.Set(byte(lca.leftIndex), lineIndex, BLOCK_EMPTY)
		grid.Set(byte(lca.rightIndex), lineIndex, BLOCK_EMPTY)
	}

	lca.leftIndex--
	lca.rightIndex++
}

func (lca LineClearAnimation) Completed() bool {
	return lca.NumLines() == 0
}
