package wikidata

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

	"database/sql"
	"encoding/json"
	"net/http"
	"net/url"

	"github.com/knakk/sparql"
	"notabug.org/apiote/gott"
)

type Result struct {
	Repo   *sparql.Repo
	Result *sparql.Results
	Work   datastructure.Work
}

func createRepo(args ...interface{}) (interface{}, error) {
	result := args[1].(*Result)
	repo, err := sparql.NewRepo("https://query.wikidata.org/sparql")
	result.Repo = repo
	return gott.Tuple(args), err
}

func createDescriptionRequest(args ...interface{}) (interface{}, error) {
	descriptionRequest := args[0].(*network.Request)
	result := args[1].(*network.Result)
	client := &http.Client{}
	language := descriptionRequest.Language[:2]
	request, err := http.NewRequest("GET", "https://inventaire.io/api/data?action=wp-extract&lang="+language+"&title="+url.QueryEscape(descriptionRequest.Id), nil)
	result.Client = client
	result.Request = request
	return gott.Tuple(args), err
}

func unmarshalDescription(args ...interface{}) (interface{}, error) {
	result := args[1].(*network.Result)
	var description struct {
		Extract string
	}
	err := json.Unmarshal(result.Body, &description)
	result.Result = description.Extract
	return gott.Tuple(args), err
}

func GetWorkDescription(article, language string, connection *sql.DB) (string, error) {
	res, err := gott.
		NewResult(gott.Tuple{&network.Request{Id: article, Language: language, Connection: connection}, &network.Result{}}).
		Bind(createDescriptionRequest).
		Bind(network.DoRequest).
		Bind(network.HandleRequestError).
		Bind(network.ReadResponse).
		Bind(unmarshalDescription).
		Finish()
	if err != nil {
		return "", err
	}
	return res.(gott.Tuple)[1].(*network.Result).Result.(string), nil
}
