import circle from '../drawers/circle'
import Vector from '../vector'
import { PhysicsObject } from '../physics'

const rand = (min, max) => Math.random() * (max - min) + min

// const initItem = item => {
// 	item.x = 400
// 	item.y = 800
// 	item.vx = rand(-4, 4)
// 	item.vy = -1 * rand(5, 10)
// 	item.health = rand(50, 100)
// }

// const createItems = n => {
// 	const items = new Array(n).fill(true).map(() => ({}))
// 	items.forEach(initItem)
// 	return items
// }

// const createParticicles = n => {
// 	const items = createItems(n)

// 	return () => {
// 		items.forEach(item => {
// 			item.x += item.vx
// 			item.y += item.vy
// 			item.health -= 1
// 			circle({
// 				position: { x: item.x, y: item.y },
// 				radius: 10,
// 				color: `rgba(100, 100, 100, ${item.health / 100})`
// 			})
// 		})

// 		items.filter(item => item.health < 0).forEach(initItem)
// 	}
// }

// export default createParticicles

const defaultDrawer = ({ position, health, color }) =>
	circle({
		position,
		radius: 5,
		// color: `rgba(100, 100, 100, ${health / 100})`
		color: `hsla(${color}, 67%, 54%, ${health / 100})`,
	})

/*
TODO:
	+ options: direction, разброс, speed
	+ infinite: reuse dead items
 */
class ParticicleSystem1 {
	constructor(n = 0, drawer = defaultDrawer) {
		this.items = []

		for (let i = 0; i < n; i++) this.push()

		this.drawer = drawer
	}

	push() {
		this.items.push({
			position: new Vector(400, 800),
			velocity: new Vector(rand(-4, 4), -1 * rand(5, 10)),
			health: rand(50, 100),
		})
	}

	process() {
		this.items.forEach(item => {
			item.position.add(item.velocity)
			item.health -= 1
			this.drawer(item)
		})

		this.items = this.items.filter(item => item.health > 0)
	}

	clear() {
		this.items = []
	}
}

class ParticicleSystem2 {
	constructor(n = 0, drawer = defaultDrawer) {
		this.items = new Array(n)
			.fill(true)
			.map(() => ({ position: new Vector(), velocity: new Vector() }))
		this.items.forEach(this.initItem)

		this.drawer = drawer
	}

	initItem(item) {
		item.position.xy(400, 800)
		item.velocity.xy(rand(-4, 4), -1 * rand(1, 10))
		item.health = rand(50, 100)
	}

	process() {
		this.items.forEach(item => {
			item.position.add(item.velocity)
			item.health -= 1
			this.drawer(item)
		})

		this.items.filter(item => item.health < 0).forEach(this.initItem)
	}
}

export default class ParticicleSystem {
	constructor(n = 0, drawer = defaultDrawer) {
		this.items = new Array(n).fill(true).map(() => new PhysicsObject())
		this.items.forEach(this.initItem)

		this.drawer = drawer
	}

	initItem(item) {
		item.position.xy(400, 800)
		item.velocity.xy(0, 0)
		item.applyForce(Vector.of(rand(-3, 3), -1 * rand(5, 15)))
		item.health = rand(50, 100)
		item.color = rand(0, 255) | 0
	}

	process() {
		this.items.forEach(item => {
			item.calculate()
			item.health -= 0.5
			this.drawer(item)
		})

		this.items.filter(item => item.health < 0).forEach(this.initItem)
	}
}
