import store from 'store'

export default class {
	getFullLines() {
		const field = store.options.objects.field

		return field.reduce((acc, row, index) => {
			const full = row.every(item => item > 0)
			if (full) acc.push(index)
			return acc
		}, [])
	}

	removeLines(linesIndexes) {
		const field = store.options.objects.field
		const width = store.options.dimensions.x

		linesIndexes.sort((a, b) => b - a)

		linesIndexes.forEach(index => field.splice(index, 1))
		linesIndexes.forEach(() => field.unshift(new Array(width).fill(0)))
	}

	update() {
		const lines = this.getFullLines()
		this.removeLines(lines)

		return lines.length
	}

	restart() {
		const [width, height] = store.options.dimensions.toArray()

		const objects = store.options.objects

		objects.field = new Array(height).fill(true)
			.map(() => new Array(width).fill(0))

		for (let y = height - 3; y < height; y++) {
			for (let i = 0; i < width - 1; i++) {
				objects.field[y][Math.random() * width | 0] = 1
			}
		}
	}
}
