package appctx

import (
	"context"
	"fmt"
	"github.com/rs/zerolog"
	"lab.zaar.be/thefish/alchemyst-go/util"
)

const (
	configKey = "config"
	loggerKey = "logger"
)

type clientCtx struct {
	context.Context
}

var ClientState clientCtx

func NewClientContext(config *util.Config, logger *zerolog.Logger) {
	ctx := context.Context(context.TODO())
	ctx = context.WithValue(ctx, configKey, config)
	ctx = context.WithValue(ctx, loggerKey, logger)
	ClientState = clientCtx{ctx}
}

func Config(c context.Context) *util.Config {
	cfg, ok := c.Value(configKey).(*util.Config)
	if !ok {
		panic(fmt.Errorf("no access to config from context"))
	}
	return cfg
}

func Logger() *zerolog.Logger {
	return getLogger(ClientState.Context)
}

func getLogger(c context.Context) *zerolog.Logger {
	logger, ok := c.Value(loggerKey).(*zerolog.Logger)
	if !ok {
		panic(fmt.Errorf("no access to logger from context"))
	}
	return logger
}

//func FromContext(appctx context.Context) (*User, bool) {
//	u, ok := appctx.Value(userKey).(*User)
//	return u, ok
//}
