package main

import (
	"flag"
	"fmt"
	"net/http"
	"os"

	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"

	"go.buzzert.net/kordophone-mock/prompt"
	"go.buzzert.net/kordophone-mock/web"
)

type LoggingHook struct {
	prompt *prompt.Prompt
}

func (t *LoggingHook) Run(e *zerolog.Event, level zerolog.Level, message string) {
	t.prompt.CleanAndRefreshForLogging()
}

func setupLogging(debug bool) {
	// Pretty logging
	log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})

	// Default level for this example is info, unless debug flag is present
	zerolog.SetGlobalLevel(zerolog.InfoLevel)
	if debug {
		zerolog.SetGlobalLevel(zerolog.DebugLevel)
	}
}

func printWelcomeMessage() {
	// Print ascii art of "Kordophone"
	fmt.Println(`
 _  __           _          _                 
| |/ /___ _ _ __| |___ _ __| |_  ___ _ _  ___ 
| ' </ _ \ '_/ _' / _ \ '_ \ ' \/ _ \ ' \/ -_)
|_|\_\___/_| \__,_\___/ .__/_||_\___/_||_\___|
                      |_|                     
    `)
}

func main() {
	debugLogging := flag.Bool("debug", false, "enable debug logging")
	authEnabled := flag.Bool("auth", false, "enable authentication")
	flag.Parse()

	setupLogging(*debugLogging)

	printWelcomeMessage()

	c := web.MockHTTPServerConfiguration{
		AuthEnabled: *authEnabled,
	}

	addr := ":5738"
	s := web.NewMockHTTPServer(c)
	httpServer := &http.Server{
		Addr:    addr,
		Handler: s,
	}

	// Populate with test data
	s.Server.PopulateWithTestData()
	log.Info().Msgf("Generated test data. %d conversations", len(s.Server.Conversations()))

	log.Info().Msgf("Listening on %s", addr)
	go httpServer.ListenAndServe()

	rl := prompt.NewPrompt(&s.Server)

	// Hook logging so we can refresh the prompt when something is logged.
	log.Logger = log.Logger.Hook(&LoggingHook{prompt: rl})

	// Read indefinitely
	err := rl.StartInteractive()
	if err != nil {
		log.Error().Err(err)
	}
}
