package main

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

	"code.justin.tv/common/twitchhttp"

	"golang.org/x/net/context"
)

func InitMetaTags(hostport string) {
	conf := twitchhttp.ClientConf{
		Host: hostport,
	}
	client, err := twitchhttp.NewClient(conf)
	if err != nil {
		log.Fatalf("Could not initialize client for rails: %v", err)
	}

	RailsClient.Client = client
}

type railsClient struct {
	twitchhttp.Client
}

var RailsClient railsClient

const (
	clientID = "jzkbprff40iqj646a697cyrvl0zt2m6"
)

// Returns HTML of the meta tags associated with this channel page
func channelMetaTags(ctx context.Context, channel string) (string, error) {
	path := fmt.Sprintf("/api/meta_tags/%s?client_id=%s", channel, clientID)

	req, err := RailsClient.NewRequest("GET", path, nil)
	if err != nil {
		return "", err
	}

	opts := twitchhttp.ReqOpts{}
	resp, err := RailsClient.Do(ctx, req, opts)
	if err != nil {
		return "", err
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	if resp.StatusCode != http.StatusOK {
		return "", errors.New("Invalid meta_tag API response: " + string(body))
	}

	return string(body), nil
}
