package game

import (
	"bytes"
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logc"
	"runtime"

	"github.com/davy66666/poker-go/src/github.com/davecgh/go-spew/spew"
)

// PrintPanicStack 产生panic时的调用栈打印
func PrintPanicStack(extras ...interface{}) interface{} {
	defer func() {
		if x := recover(); x != nil {
			ctx := context.Background()
			logc.Errorf(ctx, "Login-RabbitSender PANIC: %+v\n", x)

			// 打印堆栈信息
			for i := 0; ; i++ {
				if pc, file, line, ok := runtime.Caller(i); ok {
					logc.Errorf(ctx, "frame %d: [func: %s, file: %s, line: %d]\n",
						i, runtime.FuncForPC(pc).Name(), file, line)
				} else {
					break
				}
			}

			// 打印 extras 传入的额外数据
			if len(extras) > 0 {
				var buf bytes.Buffer
				for i, extra := range extras {
					buf.WriteString(fmt.Sprintf("EXTRA#%d DATA:\n%s\n", i, spew.Sdump(extra)))
				}
				logc.Errorf(ctx, "%s", buf.String())
			}
		}
	}()
	return nil
}
