package app

import (
	"context"
	"fmt"
	"gardening/src/app/container"
	"gardening/src/lib"
	"gardening/src/lib/error"
	"os"
)

type App struct {
	Container *container.Container
}

func (this *App) Build(ctx context.Context, env string) {
	this.checkEnv(env)

	this.Container = &container.Container{}
	this.Container.BuildContainer(env)

	this.Configure(ctx)
}

func (this *App) Run(ctx context.Context, args []string) {
	if len(args) < 2 {
		fmt.Println("No command given")
		os.Exit(1)
	}

	command := args[1]
	switch command {
	case "web":
		err := this.Container.WebCommand.Act(ctx)
		if err == nil {
			panic(erro.W("Cannot run 'web' command", err))
		}
	case "load-dictionary":
		err := this.Container.LoadDictionaryCommand.Act(context.Background())
		if err != nil {
			panic(err)
		}

	default:
		fmt.Println("Invalid command: " + command)
		os.Exit(1)
	}
}

func (this *App) Stop(ctx context.Context) {
	if this.Container.WebServer.HasServer() {
		err := this.Container.WebServer.Shutdown(ctx)
		lib.Poe(err)
	}
}

func (this *App) checkEnv(env string) {
	if env == "" {
		lib.Poe(erro.N("No env is set"))
	}
}
