package tmdb

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

	"encoding/json"
	"net/http"
	"net/url"
	"time"

	"notabug.org/apiote/gott"
)

type SearchResults struct {
	Query       string
	Page        int
	Total_pages int `json:"total_pages"`
	Results     []struct {
		Id                 int
		Media_type         string `json:"media_type"`
		Name               string
		Title              string
		First_air_date_str string `json:"first_air_date"`
		Release_date_str   string `json:"release_date"`
		Poster_path        string `json:"poster_path"`
		Profile_path       string `json:"profile_path"`
		Release_date       time.Time
	}
}

func (r SearchResults) NextPage() int {
	return r.Page + 1
}

func (r SearchResults) PrevPage() int {
	return r.Page - 1
}

type Query struct {
	query    string
	language string
	page     string
}

func createSearchQuery(args ...interface{}) (interface{}, error) {
	query := args[0].(*Query)
	result := args[1].(*network.Result)
	client := &http.Client{}
	if query.page == "" {
		query.page = "1"
	}
	url :="https://api.themoviedb.org/3/search/multi?api_key="+config.TmdbApiKey+"&language="+query.language+"&query="+url.QueryEscape(query.query)+"&page="+query.page+"&include_adult=false"
	request, err := http.NewRequest("GET", url, nil)
	result.Client = client
	result.Request = request
	return gott.Tuple(args), err
}

func unmarshalSearchResults(args ...interface{}) (interface{}, error) {
	query := args[0].(*Query)
	result := args[1].(*network.Result)
	results := &SearchResults{}
	err := json.Unmarshal(result.Body, results)
	results.Query = query.query
	for i, result := range results.Results {
		if result.Name == "" {
			result.Name = result.Title
		}
		if result.Poster_path == "" {
			result.Poster_path = result.Profile_path
		}
		results.Results[i] = result
	}
	result.Result = results
	return gott.Tuple(args), err
}

func convertSearchResultsDates(args ...interface{}) (interface{}, error) {
	results := args[1].(*network.Result).Result.(*SearchResults)
	for i, result := range results.Results {
		if result.Release_date_str != "" {
			date, err := time.Parse("2006-01-02", result.Release_date_str)
			if err != nil {
				return gott.Tuple(args), err
			}
			result.Release_date = date
			results.Results[i] = result
		}
		if result.First_air_date_str != "" {
			date, err := time.Parse("2006-01-02", result.First_air_date_str)
			if err != nil {
				return gott.Tuple(args), err
			}
			result.Release_date = date
			results.Results[i] = result
		}
	}
	return gott.Tuple(args), nil
}

func Search(query, language, page string) (*SearchResults, error) {
	results, err := gott.
		NewResult(gott.Tuple{&Query{query, language, page}, &network.Result{}}).
		// todo parse query -> search (when no nigmas) |-> discover (when nigmas)
		Bind(createSearchQuery).
		Bind(network.DoRequest).
		Bind(network.HandleRequestError).
		Bind(network.ReadResponse).
		Bind(unmarshalSearchResults).
		Bind(convertSearchResultsDates).
		Finish()

	if err != nil {
		return &SearchResults{}, err
	} else {
		return results.(gott.Tuple)[1].(*network.Result).Result.(*SearchResults), nil
	}
}
