package tmdb

import (
	"notabug.org/apiote/gott"

	"encoding/json"
	"math/rand"
	"net/http"
	"strconv"
)

type randomFilms struct {
	Results []struct {
		Title string
	}
}

func createRandomRequest(args ...interface{}) (interface{}, error) {
	tmdbRequest := args[0].(TmdbRequest)
	client := &http.Client{}
	page := strconv.FormatInt(rand.Int63n(100), 10)
	request, err := http.NewRequest("GET", "https://api.themoviedb.org/3/discover/movie?api_key="+API_KEY+"&language="+tmdbRequest.language+"&sort_by=popularity.desc&include_adult=false&include_video=false&page="+page+"&with_genres=35", nil)
	args[1] = client
	args[2] = request
	return gott.Tuple(args), err
}

func unmarshalRandom(args ...interface{}) (interface{}, error) {
	body := []byte(args[3].(string))
	films := &randomFilms{}
	err := json.Unmarshal(body, films)
	args[3] = films.Results[rand.Intn(len(films.Results))].Title
	return gott.Tuple(args), err
}

func GetRandomComedy(language string) (string, error) {
	film, err := gott.
		NewResult(gott.Tuple{TmdbRequest{"", "", language, ""}, nil, nil, nil, nil}).
		Bind(createRandomRequest).
		Bind(doRequest).
		Bind(handleRequestError).
		Bind(readResponse).
		Bind(unmarshalRandom).
		Finish()

	if err != nil {
		return "", err
	} else {
		return film.(gott.Tuple)[3].(string), nil
	}
}
