package main

import (
	"fmt"

	"opslag.de/schobers/allg5"

	"opslag.de/schobers/krampus19/alui"
)

type levelSelect struct {
	alui.Menu

	ctx *Context

	packID string
	pack   levelPack
}

func (s *levelSelect) Enter(ctx *Context) error {
	s.ctx = ctx
	s.pack = s.ctx.Levels.ByID(s.packID)
	s.Init()
	name := func(i int, steps int) string {
		if steps == 0 {
			return fmt.Sprintf("Level %d", i)
		}
		return fmt.Sprintf("Level %d (%d)", i, steps)
	}
	if s.ctx.Levels.MustSelect() {
		s.AddChild(newHeader(fmt.Sprintf("Select a '%s' level", s.pack.name)))
	} else {
		s.AddChild(newHeader("Select a level"))
	}
	for i, id := range s.pack.order {
		levelID := id
		s.Add(name(i+1, s.ctx.Progress.Level(s.packID, levelID).Steps), func() {
			s.ctx.Navigation.PlayLevel(s.packID, levelID)
		})
	}
	if s.ctx.Levels.MustSelect() {
		s.Add("Select level pack", func() { s.ctx.Navigation.SelectPack() })
	}
	s.Add("Back to main menu", func() { s.ctx.Navigation.ShowMainMenu() })
	return nil
}

func (s *levelSelect) Handle(e allg5.Event) {
	switch e := e.(type) {
	case *allg5.KeyDownEvent:
		switch e.KeyCode {
		case allg5.KeyEscape:
			s.ctx.Navigation.ShowMainMenu()
		}
	}
	s.Menu.Handle(e)
}

func (s *levelSelect) Leave() {}
