package rollbar

import (
	"fmt"
	"net/http"
	"os"

	"code.justin.tv/common/golibs/bininfo"
	"code.justin.tv/common/golibs/errorlogger"

	"github.com/heroku/rollbar"
)

type ErrorLogger struct {
	rollbar rollbar.Client
}

const (
	entireStack    = 0
	truncatedStack = 7
)

// NewErrorLogger creates a *rollbar.ErrorLogger instead of the interface errorlogger.ErrorLogger
func NewErrorLogger(token, env string) *ErrorLogger {
	hostname, err := os.Hostname()
	if err != nil {
		hostname = "unknown"
	}

	rollbar := rollbar.New(token, env, bininfo.Revision(), hostname, "")
	return &ErrorLogger{rollbar}
}

// Deprecated: Use NewErrorLogger
func NewRollbarLogger(token, env string) errorlogger.ErrorLogger {
	return NewErrorLogger(token, env)
}

func (l *ErrorLogger) Error(err error) {
	l.rollbar.ErrorWithStackSkip(rollbar.ERR, err, entireStack)
}

func (l *ErrorLogger) RequestError(r *http.Request, err error) {
	l.rollbar.RequestErrorWithStackSkip(rollbar.ERR, r, err, entireStack)
}

func (l *ErrorLogger) RequestPanic(r *http.Request, p interface{}) {
	err := fmt.Errorf("panic: %v", p)
	l.rollbar.RequestErrorWithStackSkip(rollbar.ERR, r, err, truncatedStack)
}

func (l *ErrorLogger) Info(msg string) {
	l.rollbar.Message(rollbar.INFO, msg)
}

// SetCustom calls through to the heroku/rollbar.Client SetCustom method for adding arbitrary metadata
func (l *ErrorLogger) SetCustom(custom map[string]interface{}) {
	l.rollbar.SetCustom(custom)
}
