/**
= 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 connect

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"

	// "log"
	"io/ioutil"
	"net/http"
	"strings"

	//	"net/url"
	def "Toolbox/defaults"
	tol "Toolbox/goDataverse/tools"
)

func GetRequest(url string, params, header tol.ColMap) ([]byte, error) {
	client := &http.Client{}
	req, _ := http.NewRequest("GET", url, nil)
	for k, v := range header {
		req.Header.Add(k, v)
	}
	query := req.URL.Query()
	for k, v := range params {
		query.Add(k, v)
	}

	req.URL.RawQuery = query.Encode()
	def.LogMessage("GetRequest(url.encode)", url, def.DEF_logdebg)
	res, err := client.Do(req)
	if err != nil {
		def.LogError("GetRequest(do)", err)
	} else {
		defer res.Body.Close()
		b, err := ioutil.ReadAll(res.Body)
		if err == nil {
			return b, err
		}
	}
	return []byte(""), err
}

func GetRequestMap(_url string, params tol.ColMapInt, header tol.ColMap) ([]byte, error) {
	client := &http.Client{}
	// _url = _url + "&fq=(title:1)"
	// _url = strings.Replace(_url, "*", `((title:2.+OR+title:Ebene))`, -1)
	def.LogMessage("GetRequestMap(map)", _url, def.DEF_logdebg)
	req, _ := http.NewRequest("GET", _url, nil)
	for k, v := range header {
		req.Header.Add(k, v)
	}
	query := req.URL.Query()
	for _, ival := range params {
		for k, v := range ival {
			def.LogMessage("GetRequestMap(values)", fmt.Sprintf("%v: %v (%v)", k, v, ival), def.DEF_logdebg)
			query.Add(k, v)
		}
	}
	//
	req.URL.RawQuery = query.Encode()
	def.LogMessage("GetRequestmap(encode)", req.URL.String(), def.DEF_logdebg)
	req.URL.RawQuery = strings.Replace(req.URL.RawQuery, "_q_=", "q=", -1)
	def.LogMessage("GetRequestMap(replac)", req.URL.String(), def.DEF_logdebg)
	res, err := client.Do(req)
	if err == nil {
		defer res.Body.Close()
		b, err := ioutil.ReadAll(res.Body)
		if err == nil {
			return b, err
		}
	}
	return []byte(""), err
}

func PostRequest(url string, params, header tol.ColMap) ([]byte, error) {
	client := &http.Client{}
	postData, err := json.Marshal(params)
	def.LogMessage("PostRequest(data)", fmt.Sprintf("%v", postData), def.DEF_logdebg)
	req, _ := http.NewRequest("POST", url, bytes.NewReader(postData))
	if err == nil {
		for k, v := range header {
			req.Header.Add(k, v)
		}
		res, err := client.Do(req)
		if err == nil {
			defer res.Body.Close()
			b, err := ioutil.ReadAll(res.Body)
			if err == nil {
				return b, err
			}
		}
	}
	return []byte(""), err
}

func PostRequestB(url string, postData []byte, header tol.ColMap) ([]byte, error) {
	client := &http.Client{}
	req, err := http.NewRequest("POST", url, bytes.NewReader(postData))
	if err == nil {
		for k, v := range header {
			req.Header.Add(k, v)
		}
		res, err := client.Do(req)
		if err == nil {
			defer res.Body.Close()
			b, err := ioutil.ReadAll(res.Body)
			return b, err
		}
	}
	return []byte(""), err
}

func DeleteRequest(url string, header tol.ColMap) ([]byte, error) {
	client := &http.Client{}
	req, _ := http.NewRequest("DELETE", url, nil)

	for k, v := range header {
		req.Header.Add(k, v)
	}
	def.LogMessage("DeleteRequest(url)", req.URL.String(), def.DEF_logdebg)
	res, _ := client.Do(req)
	//def.LogMessage("DeleteRequest(do)", res.Request.Header., def.DEF_logdebg)
	b, err := ioutil.ReadAll(res.Body)
	res.Body.Close()

	return b, err
}

func Redirect(_w http.ResponseWriter, _r *http.Request, _url string) {
	// remove/add not default ports from _r.Host
	target := _url
	// if len(_r.URL.RawQuery) > 0 {
	// 	target += "?" + _r.URL.RawQuery
	// }
	log.Printf("redirect to: %s", target)
	reponse, err := http.Get(_url)
	body, err := ioutil.ReadAll(reponse.Body)
	if err != nil {
		panic(err)
	}
	fmt.Println("response body", reponse.Body)
	_w.Write(body)
	log.Printf("redirect to: %s, %v, %v", target, string(body), err)
	//http.Redirect(_w, _r, target, http.StatusSeeOther)
}
