package util

import (
	"encoding/json"
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"strconv"

	"code.justin.tv/common/chitin"
	"code.justin.tv/common/golibs/statsd"

	"github.com/stvp/rollbar"
	"golang.org/x/net/context"
)

type Nothing struct {}

// ErrorResponse represents a JSON error.
type ErrorResponse struct {
	Error         string
	VerboseError  string
	StatusCode    int
	StatusMessage string
}

var Stats statsd.Stats

// JSONError will format and return a JSON error. Msg is sent to the user and
// err is logged.
func JSONError(w http.ResponseWriter, statusCode int, msg string, err error) {
	log.Printf("error StatusCode=%d msg=%q err=%q", statusCode, msg, err)
	w.WriteHeader(statusCode)

	rollbar.ErrorWithStack(rollbar.ERR, err, rollbar.BuildStack(0))

	if jsonErr := json.NewEncoder(w).Encode(&ErrorResponse{
		Error:         msg,
		StatusCode:    statusCode,
		StatusMessage: http.StatusText(statusCode),
		VerboseError:  err.Error(),
	}); jsonErr != nil {
		panic(jsonErr)
	}
}

// MustSetupStatsd ensures that statsd is setup
func MustSetupStatsd(host string, port int, prefix string) {
	statsdAddr := net.JoinHostPort(host, strconv.Itoa(port))
	statsdClient, err := statsd.Dial("udp", statsdAddr, statsd.StatsConfig{
		Rate:   1.0,
		Prefix: prefix,
	})
	if err != nil {
		panic(err)
	}

	Stats = statsdClient
}

// MustTraceContext is a small helper function that wraps getting a chitin
// context in a panic.
func MustTraceContext() context.Context {
	ctx, err := chitin.ExperimentalTraceContext(context.Background())
	if err != nil {
		panic(err)
	}

	return ctx
}

var haproxyHostPort = "localhost:12256"
var videoshimHostPort = "video-shim.internal.twitch.tv:5151"

func VodAPIURL() string {
	hostport := haproxyHostPort
	if os.Getenv("ENVIRONMENT") != "production" {
		hostport = videoshimHostPort
	}
	return fmt.Sprintf("http://%v/api/internal/vods", hostport)
}
