/*
    Hurry Curry! - a game about cooking
    Copyright (C) 2026 Hurry Curry! Contributors

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, version 3 of the License only.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

*/
import { MapLayer } from "./mod.ts";
import { System } from "../system.ts";
import { V2 } from "../util.ts";
import { player_controller } from "../main.ts";

export class SParticles extends System implements MapLayer {
    particles: Set<Particle> = new Set()
    particles_to_remove: Set<Particle> = new Set()
    override tick(dt: number): void {
        this.particles.forEach(p => p.tick(dt) ? {} : this.particles_to_remove.add(p))
        this.particles_to_remove.forEach(p => this.particles.delete(p))
        this.particles_to_remove = new Set()
    }

    override input(ev: KeyboardEvent, down: boolean): boolean {
        if (down && ev.code == "KeyE") {
            this.create_splash(player_controller.get_interact_target() ?? { x: 0, y: 0 }, 0.8)
            return true
        }
        return false
    }

    draw_map_layer(ctx: CanvasRenderingContext2D): void {
        ctx.save()
        this.particles.forEach(p => p.draw(ctx))
        ctx.restore()
    }

    create_splash(pos: V2, hue: number) {
        for (let i = 0; i < 64; i++) {
            const p = new Particle()
            p.px = pos.x + 0.5
            p.py = pos.y + 0.5
            const a = Math.random() * Math.PI * 2
            const r = Math.sqrt(Math.random()) * 5.
            p.vx = Math.sin(a) * r
            p.vy = Math.cos(a) * r
            p.decay = 4.
            p.tr = Math.sqrt(Math.random()) * 1.
            p.c = `hsl(${Math.random() * 0.2 - 0.1 + hue}turn, 100%, 50%)`
            p.r = Math.random() * 0.1 + 0.03
            this.particles.add(p)
        }
    }
}

class Particle {
    c = "red"
    r = 0.05
    tr = 0
    px = 0
    py = 0
    vx = 0
    vy = 0
    decay = 1

    tick(dt: number) {
        this.tr -= dt
        this.px += this.vx * dt;
        this.py += this.vy * dt;
        this.vx *= Math.exp(-dt * this.decay)
        this.vy *= Math.exp(-dt * this.decay)
        return this.tr > 0.
    }
    draw(ctx: CanvasRenderingContext2D) {
        ctx.fillStyle = this.c
        ctx.globalAlpha = Math.min(1, this.tr * 5.)
        ctx.beginPath()
        ctx.arc(this.px, this.py, this.r, 0, Math.PI * 2)
        ctx.fill()
    }
}

