package eas

import (
	"bytes"
	"compress/gzip"
	"encoding/json"
	"io/ioutil"
	"net/http"
)

type PMMLRequest struct {
	EasRequest
}

func (r *PMMLRequest) Invoke(requestData interface{}) (body interface{}, err error) {
	data, _ := json.Marshal(requestData)
	// start := time.Now()
	// fmt.Println(string(data))
	var buf bytes.Buffer
	zw := gzip.NewWriter(&buf)
	_, err = zw.Write(data)
	if err != nil {
		return nil, err
	}
	zw.Close()

	// fmt.Println("buffer", utils.CostTime(start))
	req, err := http.NewRequest("POST", r.url, &buf)
	if err != nil {
		return
	}

	headers := map[string][]string{
		"Authorization":    {r.auth},
		"Content-Encoding": {"gzip"},
	}
	req.Header = headers

	easClient.Timeout = r.timeout

	response, err := easClient.Do(req)
	if err != nil {
		return
	}

	defer response.Body.Close()

	reqBody, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return
	}

	body = string(reqBody)
	// fmt.Println("request end", utils.CostTime(start))
	// fmt.Println(string(reqBody))
	// request := gorequest.New()
	// _, body, errs := request.Post(r.url).
	// Set("Authorization", r.auth).
	// Send(requestData).
	// Set("Content-Encoding", "gzip").
	// Send(string(buf.Bytes())).
	// Type("text").
	// Timeout(r.timeout).
	// End()
	// if errs != nil {
	// err = errs[0]
	// return
	// }

	return
}
