package curl

import (
	"bytes"
	"compress/gzip"
	"fmt"

	//"fmt"
	"io/ioutil"
	"net/http"
	"ssp/logger"
	"strings"
	"time"
)

func SendRequest(curlChannel chan<- []byte, jsonReq []byte, pingUrl string, version string, tmax int, gZip *int) {

	var (
		//gzjsonReq string
		req *http.Request
		err error
	)

	//~ fmt.Println(string(jsonReq))

	method := "POST"
	payload := strings.NewReader(string(jsonReq))

	if *gZip == 1 {

		//gzjsonReq = base64.StdEncoding.EncodeToString(jsonReq)
		var buf bytes.Buffer
		g := gzip.NewWriter(&buf)
		if _, err = g.Write(jsonReq); err != nil {
			logger.Log.Println("Error ", err.Error())
			return
		}
		if err = g.Close(); err != nil {
			logger.Log.Println("Error ", err.Error())
			return
		}

		//payload1 := strings.NewReader(gzjsonReq)
		//req, err = http.NewRequest(method, pingUrl, payload1)
		fmt.Println("GZIP REQ:", buf)
		req, err = http.NewRequest(method, pingUrl, &buf)
		req.Header.Set("Content-Encoding", "gzip")
	} else {
		req, err = http.NewRequest(method, pingUrl, payload)
		req.Header.Add("Content-Type", "application/json")
	}
	if err != nil {
		logger.Log.Println("Error =0", err.Error())
	}
	/* caCert, err := ioutil.ReadFile("../log/advanced_garritz_com_ca0c1_02c47_1598460890_57f25a77135453b5677ce1f5cef23df4.crt")
	if err != nil {
		logger.Log.Println("Error ", err.Error())
	}
	caCertPool := x509.NewCertPool()
	caCertPool.AppendCertsFromPEM(caCert)

	client := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{
				RootCAs: caCertPool,
			},
		},
	} */
	client := &http.Client{
		Timeout: time.Duration(tmax) * time.Millisecond,
	}
	req.Header.Add("x-openrtb-version", version)
	res, err := client.Do(req)

	if err != nil {
		curlChannel <- []byte{}

		logger.Log.Println("REQ", req)
		logger.Log.Println("Error =1", err.Error())
		return
	}

	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)

	if err != nil {
		curlChannel <- []byte{}
		logger.Log.Println("Error =2", err.Error())
		return
	}

	//~ fmt.Println(string(body))
	curlChannel <- body
}

func SendLNotices(lnotices []string) {

	return

	for _, v := range lnotices {
		// Make a cURL get request
		resp, err := http.Get(v)

		// Log error when request not successful
		if err != nil {
			logger.Log.Println("Error ", err.Error())
		}

		// Close response body
		defer resp.Body.Close()
	}
}

func SendWNotices(wnotices string) {

	return

	// Make a cURL get request
	resp, err := http.Get(wnotices)

	// Log error when request not successful
	if err != nil {
		logger.Log.Println("Error ", err.Error())
	}

	// Close response body
	defer resp.Body.Close()
}
