package playhead

import (
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/stvp/rollbar"
)

var thumbnailHost = "http://vod.internal.twitch.tv:8080"

func (p *Playhead) Thumbnail() ([]byte, error) {
	ps := p.CurrentVod.Properties
	path := ps.Thumbnails[0]["path"].(string)

	// This is a hack around an existing bug where some thumbnail paths are prefixed with / and others aren't
	if string(path[0]) != "/" {
		path = fmt.Sprintf("/%v", path)
	}

	uri := fmt.Sprintf("%v/%v%v", thumbnailHost, ps.URI, path)

	response, err := http.Get(uri)
	if err != nil {
		rollbar.ErrorWithStack(rollbar.WARN, err, rollbar.BuildStack(0))
		return []byte{}, err
	}
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		rollbar.ErrorWithStack(rollbar.WARN, err, rollbar.BuildStack(0))
		return []byte{}, err
	}
	return body, nil
}
