package app

import (
	"common/log"
	"context"
	"errors"
	"fmt"
	"gateway/config"
	"gateway/internal/net/http_gateway"
	"net/http"
	"sync"
)

// ModuleWebServer Web服务模块
type ModuleWebServer struct {
	wg     *sync.WaitGroup
	server *http.Server
}

func (m *ModuleWebServer) init() error {
	m.wg = &sync.WaitGroup{}
	return nil
}

func (m *ModuleWebServer) start() error {
	m.wg.Add(1)
	go func() {
		defer m.wg.Done()
		m.server = &http.Server{
			Addr:    fmt.Sprintf("%v:%v", config.Get().Serve.Http.Address, config.Get().Serve.Http.Port),
			Handler: http_gateway.InitRouter(),
		}
		if err := m.server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Errorf("http server failed: %v", err.Error())
		}
		log.Infof("http server stop.")
	}()
	return nil
}

func (m *ModuleWebServer) stop() error {
	if err := m.server.Shutdown(context.Background()); err != nil {
		log.Errorf("stop http server failed: %v", err)
	}
	m.wg.Wait()
	return nil
}
