package utils

import (
	"context"

	"gd_management_gateway/common.in/span"
	beegoctx "github.com/astaxie/beego/context"
	"github.com/smallnest/rpcx/share"
)

func NewContextFromBeegoCtx(ctx *beegoctx.Context) context.Context {
	// request metadata
	metadata := make(map[string]string)
	if spanID, err := span.ParseSpanID(ctx.Input.Header("span")); err == nil {
		metadata["span"] = span.NewSpanID(*spanID).String()
	}

	return context.WithValue(context.Background(), share.ReqMetaDataKey, metadata)
}

func NewContextFromRpcCtx(ctx context.Context) context.Context {
	// request metadata
	metadata := make(map[string]string)
	if preMetadata := ctx.Value(share.ReqMetaDataKey).(map[string]string); preMetadata != nil {
		if v, ok := preMetadata["span"]; ok {
			if spanID, err := span.ParseSpanID(v); err == nil {
				metadata["span"] = span.NewSpanID(*spanID).String()
			}
		}
	}

	return context.WithValue(context.Background(), share.ReqMetaDataKey, metadata)
}

func GetSpanFromRpcCtx(ctx context.Context) (spanID *span.SpanID, err error) {
	if preMetadata := ctx.Value(share.ReqMetaDataKey).(map[string]string); preMetadata != nil {
		if v, ok := preMetadata["span"]; ok {
			spanID, err = span.ParseSpanID(v)
		}
	}

	return
}

func GetMethodFromRpcCtx(ctx context.Context) (method string) {
	if preMetadata := ctx.Value(share.ReqMetaDataKey).(map[string]string); preMetadata != nil {
		if v, ok := preMetadata["method"]; ok {
			method = v
		}
	}

	return
}
