package main

import (
	"log"

	"opslag.de/schobers/allg5"
	"opslag.de/schobers/geom"
	"opslag.de/schobers/krampus19/alui"
	"opslag.de/schobers/krampus19/gut"
)

type console struct {
	alui.ControlBase

	cons *gut.Console

	buffer  *allg5.Bitmap
	bufferN int
	height  float32
	offset  float32
}

func newConsole(cons *gut.Console) *console {
	return &console{cons: cons, height: 300}
}

func (c *console) Render(ctx *alui.Context, bounds geom.RectangleF32) {
	back := allg5.NewColorAlpha(0, 0, 0, 0xaf)
	line := allg5.NewColor(0x7f, 0x7f, 0x7f)

	c.height = geom.Min32(c.height, bounds.Dy())
	top := geom.Max32(bounds.Max.Y-c.height, bounds.Min.Y)
	allg5.DrawFilledRectangle(bounds.Min.X, top, bounds.Max.X, bounds.Max.Y, back)
	allg5.DrawLine(bounds.Min.X, top, bounds.Max.X, top, line, 1)

	font := ctx.Fonts.Get("console")
	lineHeight := font.Height() * 1.1

	size := geom.Pt(int(bounds.Dx()-8), int(c.height-8))
	if c.buffer == nil || c.buffer.Height() != size.Y || c.buffer.Width() != size.X {
		if c.buffer != nil {
			c.buffer.Destroy()
		}
		buffer, err := allg5.NewVideoBitmap(size.X, size.Y)
		if err != nil {
			log.Fatal("Couldn't create new video bitmap")
		}
		c.buffer = buffer
		c.bufferN = -1
	}

	messages := c.cons.Messages()
	messagesN := len(messages)
	if messagesN != c.bufferN {
		c.buffer.SetAsTarget()

		allg5.ClearToColor(allg5.NewColorAlpha(0, 0, 0, 0))

		size := geom.PtF32(float32(size.X), float32(size.Y))
		totalHeight := lineHeight * float32(messagesN)
		if totalHeight < size.Y {
			c.offset = size.Y - totalHeight
		}
		messageTop := size.Y - totalHeight - c.offset
		for _, m := range messages {
			if messageTop <= size.Y && (messageTop+lineHeight) >= 0 {
				ctx.Fonts.DrawFont(font, 0, messageTop, ctx.Palette.Text, m)
			}
			messageTop += lineHeight
		}
		c.bufferN = messagesN
		ctx.Display.SetAsTarget()
	}
	c.buffer.Draw(bounds.Min.X+4, bounds.Max.Y-c.height+4)
}
