package ecs.systems;

import ecs.components.*;
import ecs.core.Entity;
import ecs.core.System;
import res.display.Sprite;
import res.geom.Vector2;

class SpawnOreSystem extends System {
	final getOreSprite:Void->Sprite;

	public function new(getOreSprite:Void->Sprite) {
		super(HasOre, Kill, Death);

		this.getOreSprite = getOreSprite;

		renderable = false;
	}

	override function updateEntity(entity:Entity, dt:Float) {
		final hasOre = entity.get(HasOre);

		entity.remove(hasOre);

		for (_ in 0...hasOre.ore) {
			final oreEntity = new Entity('ore');

			final ra = Math.random() * (Math.PI * 2);

			final v = Vector2.xy(Math.cos(ra), Math.sin(ra));

			final speed = 30 + Math.random() * 10;

			final triggerRadius = entity.get(TriggerRadius);

			final r = triggerRadius != null ? triggerRadius.radius : 5;

			final spatial = entity.get(Spatial).clone();
			spatial.x += v.x * r;
			spatial.y += v.y * r;

			oreEntity.add(spatial);

			final spriteComponent = new ecs.components.Sprite(getOreSprite(), 0.5, 0.5);
			spriteComponent.flipX = Math.random() > 0.5;
			spriteComponent.flipY = Math.random() > 0.5;
			spriteComponent.wrap = false;

			final or = spriteComponent.sprite.width / 2;

			oreEntity.add(spriteComponent);
			oreEntity.add(new Velocity(v.x * speed, v.y * speed));
			oreEntity.add(new Acceleration(-40));
			oreEntity.add(new CollisionCircle(or));
			oreEntity.add(new ResolveCollision());
			oreEntity.add(new CollisionResult());
			oreEntity.add(new Ore(hasOre.valuePerPiece));
			oreEntity.add(new Emitter(0.1, 1, or, 1, [5, 13]));

			engine.add(oreEntity);
		}
	}
}
