package auth

import (
	"crypto/hmac"
	"crypto/sha1"
	"encoding/json"
	"net/http"

	"github.com/stvp/rollbar"
)

var usherManifestKeysURL = "http://usher.twitch.tv/hls_transcode/manifest_keys.json"

type KeySet []string

var key string

func init() {
	var keySet KeySet

	response, err := http.Get(usherManifestKeysURL)
	if err != nil {
		rollbar.ErrorWithStack(rollbar.ERR, err, rollbar.BuildStack(0))
	}
	defer response.Body.Close()

	if response.StatusCode != http.StatusOK {
		rollbar.ErrorWithStack(rollbar.ERR, err, rollbar.BuildStack(0))
	}
	json.NewDecoder(response.Body).Decode(&keySet)

	key = keySet[0]
}

func Sign(message string) ([]byte, error) {
	mac := hmac.New(sha1.New, []byte(key))
	if _, err := mac.Write([]byte(message)); err != nil {
		return nil, err
	}
	return mac.Sum(nil), nil
}
