package system

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
	"os/signal"
	"runtime"
	"syscall"
)

const (
	SIG_USR1 = syscall.Signal(10)
)

var (
	sigs chan os.Signal
)

func DumpToJSON(s interface{}) string {
	marshal, err := json.Marshal(s)
	if err != nil {
		return err.Error()
	}
	return string(marshal)
}

func WaitSignal() {
	// 创建一个通道来接收信号
	sigs = make(chan os.Signal, 1)
	// 监听指定的信号
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, SIG_USR1)

	// 主循环，等待信号
	for {
		sig := <-sigs
		switch sig {
		case syscall.SIGINT, syscall.SIGTERM:
			// 接收到 SIGINT 或 SIGTERM 信号，退出程序
			log.Println("Received signal to terminate program")
			return
		case SIG_USR1:
			// 接收到 SIGUSR1 信号，dump 内存
			log.Println("Received signal to dump memory")
			stack := make([]byte, 1<<14)         // 分配足够的空间
			length := runtime.Stack(stack, true) // 获取堆栈信息
			fmt.Fprintf(os.Stderr, "Stack trace:\n%s\n", stack[:length])

			// if err := pprof.WriteHeapProfile(f); err != nil {
			// 	log.Fatalf("could not write memory profile: %v", err)
			// }
			// log.Println("Memory dumped to mem.pprof")
		default:
			log.Printf("Received unknown signal: %v", sig)
		}
	}
}

func TriggerSignal(signal os.Signal) {
	sigs <- signal
}
