package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"sync"
)

var apiPort = "8083"

var apiAddr = "0.0.0.0:" + apiPort
var uiAddr = "0.0.0.0:8084"
var externalApiAddr = "https://localhost:" + apiPort

func main() {
	stop := make(chan os.Signal, 1)
	signal.Notify(stop, os.Interrupt)
	wg := &sync.WaitGroup{}

	if os.Getenv("UI_ADDR") != "" {
		uiAddr = os.Getenv("UI_ADDR")
	}

	if os.Getenv("EXT_ADDR") != "" {
		externalApiAddr = "https://" + os.Getenv("EXT_ADDR") + ":" + apiPort
	}

	srv := NewServer(apiAddr, uiAddr)
	srv.LoadData("./data/data.db")

	wg.Add(1)
	go func() {
		if err := srv.ListenAndServeUI(); err != nil && err != http.ErrServerClosed {
			panic(fmt.Errorf("err listenAndServe ui: %v", err))
		}
	}()

	wg.Add(1)
	go func() {
		if err := srv.ListenAndServeAPI(); err != nil && err != http.ErrServerClosed {
			panic(fmt.Errorf("err listenAndServe api: %v", err))
		}
	}()

	<-stop

	go func() {
		log.Println("Shutdown api server...")
		srv.ShutdownAPI(context.Background())
		wg.Done()
		log.Println("Server.shutdown...")
	}()

	go func() {
		log.Println("Shutdown ui server...")
		srv.ShutdownUI(context.Background())
		wg.Done()
		log.Println("Server.shutdown...")
	}()
	wg.Wait()
}
