package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"log"
	"net/http"
	"time"
)

var httpClient *http.Client
var fakeClient = false

func httpPost(url string, data interface{}) error {
	log.Println("-> POST", url)
	if fakeClient {
		//log.Println("httpPost:data> fake client ")
		return nil
	}
	if bs, e := json.Marshal(data); nil != e {
		return e
	} else if resp, e := httpClient.Post(url, "application/json", bytes.NewBuffer(bs)); nil != e {
		return e
	} else if resp.StatusCode != http.StatusOK {
		return errors.New("invalid resp status: " + resp.Status)
	} else {
		return nil
	}
}

func httpGet(url string, resp interface{}) error {
	log.Println("-> GET", url)
	return nil
}

func httpPostEx(url string, data interface{}, retries int) error {
	var err error
	for i := 0; i < retries; i++ {
		if err = httpPost(url, data); nil != err {
			log.Println("-> >>", err)
			time.Sleep(1 * time.Second)
		} else {
			return nil
		}
	}
	return err
}

func init() {
	httpClient = http.DefaultClient
}
