package mainwindow

import (
	"context"
	"fmt"
	"lab.zaar.be/thefish/alchemyst-go/engine/types"
	"lab.zaar.be/thefish/alchemyst-go/util/appctx"
	blt "lab.zaar.be/thefish/bearlibterminal"
)

type MainWindow struct {
	types.Rect
	ctx    context.Context
	layers map[string]types.Renderable
}

func Init(ctx context.Context) *MainWindow {
	appctx.Logger().Info().Msgf("Opening main window...")
	mw := MainWindow{ctx: ctx, layers: make(map[string]types.Renderable, 0)}
	mw.Open()
	return &mw
}



func (mw *MainWindow) AddLayer(name string, idx int, colorName string) *MainWindow {
	c := blt.ColorFromName(colorName)
	mw.layers[name] = &Layer{Idx: idx, defaultColor: c}
	return mw
}

func (mw *MainWindow) GetLayer(name string) *Layer {
	if layer, ok := mw.layers[name]; ok {
		return layer.(*Layer)
	}
	appctx.Logger().Fatal().Msgf("No layer with such name %s", name)
	return nil
}

func (mw *MainWindow) Open() {
	config := appctx.Config(mw.ctx)
	blt.Open()
	//blt.Set("window: size=80x25, title="+config.Title+" v"+string(version)+"; font: ./fonts/Monaco-Linux.ttf, size=10")
	blt.Set(
		fmt.Sprintf(
			//"window: size=%dx%d, title='%s v%s'; font: ./assets/fonts/bitmap/ibmnew8x12.png, size=8x12;",
			"window: size=%dx%d, title='%s %s'; font: %s, size=%s;",
			//"window: size=%dx%d, title='%s v%s'",
			config.MainWindowSizeX,
			config.MainWindowSizeY,
			config.Title,
			config.Version,
			config.Font,
			config.FontSize,
		),
	)
	mw.Rect = types.NewRect(0,0, config.MainWindowSizeX, config.MainWindowSizeY)
}

func (mw *MainWindow) Close() {
	appctx.Logger().Info().Msg("Closing main window...")
	blt.Close()
}

func (mw *MainWindow) Render() {
	for _, l := range mw.layers {
		l.Render()
	}
}