/**
= Creative Commons Lizenzvertrag =
Diese Software ist von der archium GmbH, Gera ist lizenziert unter einer Creative Commons Namensnennung - Nicht kommerziell - Keine Bearbeitungen 4.0 International Lizenz. (http://creativecommons.org/licenses/by-nc-nd/4.0/deed.de)
Individuelle über diese Lizenz hinausgehende Berechtigungen können Sie unter https://archium.org erhalten.

= Creative Commons License =
Software by archium GmbH, Gera is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. (http://creativecommons.org/licenses/by-nc-nd/4.0/)
Individual permissions beyond the scope of this license may be available at https://archium.org.
**/

package dataset

import (
	"fmt"
	// "log"
	"strings"

	def "Toolbox/defaults"
	con "Toolbox/goDataverse/connect"
	tol "Toolbox/goDataverse/tools"

	gjs "github.com/tidwall/gjson"
)

func GetDatasetLastVersion(_dp tol.TDVParams, _id string) (string, error) {
	var imajor int64 = 1
	var iminor int64 = 0
	var state string = "draft"
	var url string = tol.GetSiteUrl(_dp) + "/api/datasets/" + _id + "/versions"
	res, err := con.GetRequest(url, tol.ColMap{},
		tol.ColMap{"X-Dataverse-key": tol.GetApiKey(_dp)})
	if err == nil {
		var ver = tol.GetObjectFromStr(fmt.Sprintf("%s", res))
		if ver.IsObject() {
			status := gjs.Get(ver.String(), "status")
			if status.String() == "OK" {
				lst := gjs.Get(ver.String(), "data")
				if lst.IsArray() {
					for _, entry := range lst.Array() {
						if entry.IsObject() {
							tmpstate := gjs.Get(entry.String(), "versionState")
							switch tmpstate.String() {
							case "DRAFT":
								break
							case "RELEASED":
								tmpmajor := gjs.Get(entry.String(), "versionNumber")
								if tmpmajor.Int() > imajor {
									imajor = tmpmajor.Int()
									iminor = gjs.Get(entry.String(), "versionMinorNumber").Int()
								} else {
									if tmpmajor.Int() == imajor {
										tmpminor := gjs.Get(entry.String(), "versionMinorNumber")
										if tmpminor.Int() > iminor {
											iminor = tmpminor.Int()
										}
									}
								}
								state = tmpstate.String()
								break
								//fmt.Println("GetDatasetLastVersion():", _id, imajor, iminor, state, gjs.Get(entry.String(), "id"))
							}
						}
					}
				}
			}
		}
	}
	// auswertung: falls keine "released" version vorhanden, dann draft zurück
	var version string = ":" + state
	switch state {
	case "RELEASED":
		version = fmt.Sprintf("%v.%v", imajor, iminor)
	}
	//
	return version, err
}

func GetDatasetByPersistentId(_dp tol.TDVParams, _persist, _version string) (string, error) {
	var persist string = _persist
	var version string = _version
	if len(persist) == 0 {
		persist = _dp.DP_datasetPid
	}
	var url string = tol.GetSiteUrl(_dp) + "/api/datasets/:persistentId/%versions%?persistentId=" + persist
	if len(version) > 0 {
		version = "versions/" + version + "/"
	} else {
		if len(_dp.DP_datasetVersion) > 0 {
			version = "versions/" + _dp.DP_datasetVersion + "/"
		}
	}
	url = strings.Replace(url, "%versions%", version, -1)
	def.LogMessage("GetDatasetByPersistentId(url)", url, def.DEF_logdebg)
	res, err := con.GetRequest(url, tol.ColMap{},
		tol.ColMap{"X-Dataverse-key": tol.GetApiKey(_dp)})
	//
	return (fmt.Sprintf("%s", res)), err
}

func GetDatasetMetadata(_dp tol.TDVParams, _id, _version string) (string, error) {
	var version string = _version
	var url string = tol.GetSiteUrl(_dp) + "/api/datasets/" + _id + "/%versions%/metadata"
	if len(version) > 0 {
		version = "versions/" + version
	} else {
		if len(_dp.DP_datasetVersion) > 0 {
			version = "versions/" + _dp.DP_datasetVersion
		} else {
			version = "versions/1.0"
		}
	}
	url = strings.Replace(url, "%versions%", version, -1)
	def.LogMessage("GetDatasetMetadata(url)", url, def.DEF_logdebg)
	res, err := con.GetRequest(url, tol.ColMap{},
		tol.ColMap{"X-Dataverse-key": tol.GetApiKey(_dp)})
	//
	return (fmt.Sprintf("%s", res)), err
}

func GetDatasetMetafield(_dp tol.TDVParams, _id string) (string, error) {
	var url string = tol.GetSiteUrl(_dp) + "/api/admin/datasetfield/" + _id
	def.LogMessage("GetDatasetMetafield(url)", url, def.DEF_logdebg)
	res, err := con.GetRequest(url, tol.ColMap{},
		tol.ColMap{"X-Dataverse-key": tol.GetApiKey(_dp)})
	//
	return (fmt.Sprintf("%s", res)), err
}

func CreateDataset(_dp tol.TDVParams, _parent, _params string) (string, error) {
	res, err := con.PostRequestB(tol.GetSiteUrl(_dp)+"/api/dataverses/"+_parent+"/datasets",
		[]byte(_params), tol.ColMap{"X-Dataverse-key": tol.GetApiKey(_dp)})
	//
	return (fmt.Sprintf("%s", res)), err
}

//
func DownloadByDataset(_dp tol.TDVParams) ([]byte, error) {
	res, err := con.GetRequest(tol.GetSiteUrl(_dp)+"/api/access/dataset/:persistentId/?persistentId="+_dp.DP_datasetPid,
		tol.ColMap{}, tol.ColMap{"X-Dataverse-key": tol.GetApiKey(_dp)})
	//
	return res, err
}
