package flow

import (
	"fmt"
)

type driverName string

const (
	// Names of all the drivers
	main      driverName = "Main"
	levelPly  driverName = "LevelPly"
	singles   driverName = "Singles"
	randomMap driverName = "RandomMap"
	newGame   driverName = "NewGame"
	loadGame  driverName = "LoadGame"
	options   driverName = "Options"
	kbd       driverName = "Keyboard"
	bridge    driverName = "Bridge"
	briefing  driverName = "Briefing"
	choices   driverName = "Choices"
	saveGame  driverName = "SaveGame"
	credits   driverName = "Credits"
	arrange   driverName = "Arrange"

	configureUltEquip      driverName = "Configure_UltEquip"
	configureVehiclesUltra driverName = "Configure_Vehicles_Ultra"

	mainGame driverName = "MainGame"
)

var (
	driverNames = []driverName{
		main, levelPly, singles, randomMap, newGame, loadGame, options, kbd,
		bridge, briefing, choices, saveGame, credits, arrange,
		configureUltEquip, configureVehiclesUltra,
		mainGame,
	}
)

func (f *Flow) returnToLastDriver(from driverName) func() {
	return func() {
		to, ok := f.returns[from]
		if !ok {
			f.exit = fmt.Errorf("Couldn't work out where to return to from %v", from)
			return
		}

		delete(f.returns, from)

		f.setDriverNow(to)
	}
}

// from is the child menu, to is the parent
func (f *Flow) returnToLastDriverNow(from driverName) error {
	to, ok := f.returns[from]
	if !ok {
		return fmt.Errorf("Couldn't work out where to return to from %v", from)
	}

	delete(f.returns, from)

	f.setDriverNow(to)
	return nil
}

func (f *Flow) setDriver(name driverName) func() {
	return func() {
		f.setDriverNow(name)
	}
}

func (f *Flow) setDriverNow(name driverName) {
	f.current = f.drivers[name]
}

// from is the parent menu, to is the child
func (f *Flow) setReturningDriver(from, to driverName) func() {
	return func() {
		f.setReturningDriverNow(from, to)
	}
}

func (f *Flow) setReturningDriverNow(from, to driverName) {
	f.returns[to] = from
	f.setDriverNow(to)
}
