package pairec

import (
	"fmt"
	"net/http"
	"os"
	"sync"
	"time"

	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/log"
	"gitlab.alibaba-inc.com/pai_biz_arch/pairec/recconf"
)

var (
	PairecApp *App
)

func init() {
	PairecApp = NewApp()
}

type App struct {
	Handlers *ControllerRegister
	Server   *http.Server
}

func NewApp() *App {
	cr := NewControllerRegister()
	app := &App{Handlers: cr, Server: &http.Server{}}

	return app
}

func (app *App) Run() {
	mode := os.Getenv("RUN_MODE")
	if mode == "COMMAND" {
		return
	}

	addr := fmt.Sprintf("%s:%d", recconf.Config.ListenConf.HttpAddr, recconf.Config.ListenConf.HttpPort)

	app.Server.Handler = app.Handlers
	app.Server.Addr = addr
	app.Server.ReadTimeout = 30 * time.Second
	app.Server.WriteTimeout = 30 * time.Second
	app.Server.MaxHeaderBytes = 1 << 20

	wg := sync.WaitGroup{}
	wg.Add(1)
	go func() {
		defer wg.Done()
		if err := app.Server.ListenAndServe(); err != http.ErrServerClosed {
			log.Error(fmt.Sprintf("server stop, err=%v", err))
		}
	}()

	fmt.Println("server start")
	wg.Wait()
	log.Flush()
}
