package ocelot.desktop.node.nodes

import ocelot.desktop.ColorScheme
import ocelot.desktop.audio.{SoundBuffers, SoundCategory, SoundSource}
import ocelot.desktop.geometry.{Size2D, Vector2D}
import ocelot.desktop.graphics.{Graphics, IconSource}
import ocelot.desktop.node.{EntityNode, LabeledEntityNode}
import ocelot.desktop.ui.UiHandler
import ocelot.desktop.ui.event.BrainEvent
import ocelot.desktop.ui.particle.Particle
import totoro.ocelot.brain.entity.traits.{Entity, Environment}
import totoro.ocelot.brain.event.NoteBlockTriggerEvent

abstract class NoteBlockNodeBase(entity: Entity with Environment) extends EntityNode(entity) with LabeledEntityNode {
  eventHandlers += {
    case BrainEvent(event: NoteBlockTriggerEvent) =>
      SoundSource.fromBuffer(
        SoundBuffers.NoteBlock(event.instrument),
        SoundCategory.Records,
        pitch = math.pow(2f, (event.pitch - 12).toFloat / 12f).toFloat,
        volume = event.volume.toFloat.min(1f).max(0f),
      ).play()

      UiHandler.root.workspaceView.particleSystem.add(new NoteParticle(event.pitch))
  }

  override def update(): Unit = {
    super.update()
    if (mouseOver || isMoving) {
      root.get.statusBar.addMouseEntry(IconSource.Icons.LMB, "Play sample")
    }
  }

  private class NoteParticle(pitch: Int) extends Particle(speed = 1.2f) {
    override def draw(g: Graphics): Unit = {
      val col = ColorScheme("Note" + pitch.min(24).max(0)).withAlpha(1 - (2 * time - 1).min(1).max(0))
      g.sprite(
        IconSource.Particles.Note,
        position + Vector2D(pitch / 24f * 40f + 5, height / 2 - 10 - 100 * time),
        Size2D(14, 20),
        col,
      )
    }
  }
}
