package app

import (
	"common/log"
	"context"
	"errors"
	"fmt"
	"gateway/config"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"net/http"
	"sync"
)

// ModulePrometheus 普罗米修斯模块
type ModulePrometheus struct {
	wg     *sync.WaitGroup
	server *http.Server
}

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

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

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