package tmdb

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

	"notabug.org/apiote/gott"
)

const (
	API_KEY = "38209d39b738776e07346a91d16a25e4"
)

type TmdbRequest struct {
	id       string
	etag     string
	language string
	subid    string
}

type HttpError struct {
	Status int
}

func (e HttpError) Error() string {
	return strconv.FormatInt(int64(e.Status), 10)
}

func doRequest(args ...interface{}) (interface{}, error) {
	TmdbRequest := args[0].(TmdbRequest)
	client := args[1].(*http.Client)
	request := args[2].(*http.Request)
	request.Header.Add("If-None-Match", TmdbRequest.etag)
	resp, err := client.Do(request)
	args[3] = resp
	return gott.Tuple(args), err
}

func handleRequestError(args ...interface{}) (interface{}, error) {
	response := args[3].(*http.Response)
	if response.StatusCode != 200 {
		return gott.Tuple(args), HttpError{response.StatusCode}
	}
	return gott.Tuple(args), nil
}

func readResponse(args ...interface{}) (interface{}, error) {
	resp := args[3].(*http.Response)
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	args[3] = string(body)
	etag := resp.Header.Get("Etag")
	args[4] = etag
	return gott.Tuple(args), err
}
