package curl

import (
	"bytes"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
)

type Request struct {
	Url        string
	Method     string
	Headers    map[string]string
	Parameters map[string]string
}

func Curl(input *Request) ([]byte, error) {

	req, err := http.NewRequest(input.Method, input.Url, getParams(input.Parameters))

	if err != nil {
		return nil, err
	}

	for key, value := range input.Headers {
		req.Header.Set(key, value)
	}

	resp, err := http.DefaultClient.Do(req)

	if err != nil {
		log.Print(err)
		return nil, err
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)

	// debug only
	//s := string(body[:])
	//fmt.Println(s)

	return body, err
}

func getParams(params map[string]string) io.Reader {

	if params != nil {

		var buffer bytes.Buffer

		for key, value := range params {
			buffer.WriteString(key + "=" + value + "&")
		}

		return strings.NewReader(strings.TrimRight(buffer.String(), "&"))
	}

	return nil
}
