package tmdb

import (
	"notabug.org/apiote/amuse/config"
	"notabug.org/apiote/amuse/network"

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

	"notabug.org/apiote/gott"
)

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

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

func unmarshalRandom(args ...interface{}) (interface{}, error) {
	result := args[1].(*network.Result)
	films := &RandomFilms{}
	err := json.Unmarshal(result.Body, films)
	result.Result = 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{&network.Request{Language: language}, &network.Result{}}).
		Bind(createRandomRequest).
		Map(network.AddHeaders).
		Bind(network.DoRequest).
		Bind(network.HandleRequestError).
		Bind(network.ReadResponse).
		Bind(unmarshalRandom).
		Finish()

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