package ocelot.desktop.ui.widget

import ocelot.desktop.OcelotDesktop
import ocelot.desktop.color.RGBAColor
import ocelot.desktop.graphics.Graphics
import ocelot.desktop.ui.UiHandler
import ocelot.desktop.ui.layout.{CopyLayout, LinearLayout}
import ocelot.desktop.ui.widget.contextmenu.ContextMenus
import ocelot.desktop.ui.widget.itemdrag.DraggedItemPool
import ocelot.desktop.ui.widget.modal.ModalDialogPool
import ocelot.desktop.ui.widget.statusbar.StatusBar
import ocelot.desktop.ui.widget.tooltip.TooltipPool
import ocelot.desktop.util.Keybind.{Fullscreen, ReloadWorkspace, UIDebug}
import ocelot.desktop.util.Keymap.Release
import ocelot.desktop.util.{DrawUtils, Orientation}
import totoro.ocelot.brain.nbt.NBTTagCompound


class RootWidget(setupDefaultWorkspace: Boolean = true) extends Widget {
  override protected val layout = new CopyLayout(this)

  root = Some(this)

  val workspaceView = new WorkspaceView
  workspaceView.root = root

  if (setupDefaultWorkspace)
    workspaceView.createDefaultWorkspace()

  val modalDialogPool = new ModalDialogPool
  val draggedItemPool = new DraggedItemPool
  val tooltipPool = new TooltipPool
  val contextMenus = new ContextMenus
  val menuBar = new MenuBar
  val statusBar = new StatusBar

  val flash = new Flash(this)

  children :+= new Widget {
    override protected val layout = new LinearLayout(this, orientation = Orientation.Vertical)
    children :+= menuBar
    children :+= workspaceView
    children :+= statusBar
  }

  children :+= modalDialogPool
  children :+= draggedItemPool
  children :+= tooltipPool
  children :+= contextMenus

  private var isDebugViewVisible = false

  eventHandlers += {
    case Release(UIDebug) =>
      isDebugViewVisible = !isDebugViewVisible

    case Release(ReloadWorkspace) =>
      OcelotDesktop.withTickLockAcquired {
        val backendNBT = new NBTTagCompound
        val frontendNBT = new NBTTagCompound
        OcelotDesktop.workspace.save(backendNBT)
        UiHandler.root.workspaceView.save(frontendNBT)
        OcelotDesktop.workspace.load(backendNBT)
        UiHandler.root.workspaceView.load(frontendNBT)
      }

    case Release(Fullscreen) =>
      UiHandler.fullScreen = !UiHandler.fullScreen
  }

  override def draw(g: Graphics): Unit = {
    super.draw(g)
    flash.draw(g)
    if (isDebugViewVisible) drawDebugView(g)
  }

  private def drawDebugView(g: Graphics): Unit = {
    for (widget <- UiHandler.getHierarchy.reverseIterator) {
      if (widget != null) {
        val b = widget.clippedBounds
        if (b.w > 1f && b.h > 1f) {
          DrawUtils.ring(g, b.x, b.y, b.w, b.h, 1, RGBAColor(255, 0, 0, 50))
        }
      }
    }
  }

  override def update(): Unit = {
    super.update()
  }
}
