package ocelot.desktop.node.nodes

import ocelot.desktop.graphics.IconSource
import ocelot.desktop.ui.event.{ClickEvent, MouseEvent}
import ocelot.desktop.ui.widget.contextmenu.{ContextMenu, ContextMenuEntry, ContextMenuIcon, ContextMenuSubmenu}
import totoro.ocelot.brain.entity.NoteBlock
import totoro.ocelot.brain.event.{EventBus, NoteBlockTriggerEvent}

class NoteBlockNode(val noteBlock: NoteBlock) extends NoteBlockNodeBase(noteBlock) {
  override def icon: IconSource = IconSource.Nodes.NoteBlock

  override def rotatable: Boolean = false

  override def setupContextMenu(menu: ContextMenu, event: ClickEvent): Unit = {
    menu.addEntry(new ContextMenuSubmenu("Instrument", Some(ContextMenuIcon(IconSource.Icons.Guitar))) {
      {
        val maxLen = NoteBlockNode.Instruments.map(_._2.length).max

        for ((instrument, name) <- NoteBlockNode.Instruments) {
          val dot = if (noteBlock.instrument == instrument) '•' else ' '

          addEntry(ContextMenuEntry(name.padTo(maxLen, ' ') + dot) {
            noteBlock.instrument = instrument
          })
        }
      }
    })

    menu.addSeparator()

    super.setupContextMenu(menu, event)
  }

  override def onClick(event: ClickEvent): Unit = {
    event match {
      case ClickEvent(MouseEvent.Button.Left, _) =>
        if (noteBlock != null) {
          EventBus.send(NoteBlockTriggerEvent(noteBlock.node.address, noteBlock.instrument, noteBlock.pitch - 1))
        }
      case _ =>
    }
    super.onClick(event)
  }
}

object NoteBlockNode {
  private val Instruments = List(
    ("bass", "Bass (Wood)"),
    ("snare", "Snare Drum (Sand)"),
    ("hat", "Hi-hat (Glass)"),
    ("basedrum", "Bass Drum (Stone)"),
    ("bell", "Glockenspiel (Gold)"),
    ("flute", "Flute (Clay)"),
    ("chime", "Chimes (Packed Ice)"),
    ("guitar", "Guitar (Wool)"),
    ("xylophone", "Xylophone (Bone)"),
    ("iron_xylophone", "Vibraphone (Iron)"),
    ("cow_bell", "Cow Bell (Soul Sand)"),
    ("didgeridoo", "Didgeridoo (Pumpkin)"),
    ("bit", "Square Wave (Emerald)"),
    ("banjo", "Banjo (Hay Bale)"),
    ("pling", "Electric Piano (Glowstone)"),
    ("harp", "Harp"),
  )
}
