package fultonlog

import (
	"fmt"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

type FultonZapLogger struct {
	l *zap.Logger
}

func FromZapLogger(l *zap.Logger) *FultonZapLogger {
	return &FultonZapLogger{
		l: l,
	}
}

// Log does a best effort logging of the given args using zap as an underlying logger
// The fulton logger expects a main message, then a series of keys and values as
// followup arguments for structured logging, like
//     fultonlogger.Log("my main message!", "KEY1", "VALUE1", "KEY2", "VALUE2")
//
// Here, we will usher this into something that zap likes by taking those keypairs
// and shoving them into zap.String() calls
//
// Implementation heavily adapted from JSON fulton logger:
// https://git-aws.internal.justin.tv/amzn/TwitchLoggingCommonLoggers/blob/mainline/json_logger.go#L35-L54
func (fzl *FultonZapLogger) Log(msg string, keyvals ...interface{}) {
	numFields := ((len(keyvals) + (len(keyvals) % 2)) / 2)
	fields := make([]zapcore.Field, numFields)
	for i := 0; i < len(keyvals); i += 2 {
		var key, value interface{}
		if i == len(keyvals)-1 {
			key, value = "UNKEYED_VALUE", keyvals[i]
		} else {
			key, value = keyvals[i], keyvals[i+1]
		}
		fields[i/2] = zap.String(fmt.Sprint(key), fmt.Sprint(value))
	}
	fzl.l.Info(msg, fields...)
}
