import SpriteCharacter from './characters/sprite';
import SpriteItem from './sprite-item';
import resources from './resources';
import { copy, distance, Vector } from './vector';

class Coins {
	private sprite: SpriteCharacter;
	private positions: Vector[] = [];

	constructor() {
		this.sprite = new SpriteCharacter(
			new SpriteItem(resources.getImage('dungeon'), 288, 272, 8, 8, 4),
		);
	}

	draw(ctx: CanvasRenderingContext2D) {
		this.positions.forEach((position) => {
			ctx.save();
			ctx.translate(position[0], position[1]);
			this.sprite.draw(ctx);
			ctx.restore();
		});
	}

	update(dt: number) {
		this.sprite.update(dt);
	}

	add(position: Vector) {
		this.positions.push(copy(position));
	}

	collect(position: Vector) {
		const newPositions = [];
		let result = 0;
		for (let i = 0; i < this.positions.length; i++) {
			const pos = this.positions[i];
			if (distance(position, pos) < 8) {
				result++;
			} else {
				newPositions.push(pos);
			}
		}
		this.positions = newPositions;
		return result;
	}
}

export default Coins;
