package prof

import (
	"context"
	"fmt"
	"net/http"
	_ "net/http/pprof"
	"time"
)

type Prof struct {
	addr       string
	enableHttp bool
	server     *http.Server
}

// @addr http 监听地址
// @enableHttp 是否需要启动 http 服务，如果为 false, addr 随便输入个什么参数
func NewProf(addr string, enableHttp bool) *Prof {
	p := &Prof{
		addr:       addr,
		enableHttp: enableHttp,
	}
	if p.enableHttp {
		p.server = &http.Server{
			Addr: addr,
		}
		go func() {
			if err := p.server.ListenAndServe(); nil != err && err != http.ErrServerClosed {
				panic(err)
			}
		}()
	}
	return p
}

func (self *Prof) Stop() {
	if self.enableHttp {
		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()

		if err := self.server.Shutdown(ctx); err != nil {
			fmt.Println("pprof shutdown error")
		}
		select {
		case <-ctx.Done():
			fmt.Println("pprof close timeout")
		}
	}
}
