package temperature

import (
	"bytes"
	"fmt"
	"io"
	"net/http"

	"git.cryptic.systems/fh-trier/go-flucky-server/pkg/types"
)

func Print(w io.Writer) error {

	t := types.Temperature{
		TemperatureID:    "1",
		TemperatureValue: "22.5",
		TemperatureDate:  "2018-10-15T23:31:28.132417Z",
		DeviceID:         "510abdfb-3d0d-4248-b0e5-94ee962c2532",
	}

	err := postTemperature(&t)
	if err != nil {
		return err
	}
	return nil
}

func postTemperature(temperature *types.Temperature) error {
	var buffer bytes.Buffer
	temperature.EncodeToJSON(&buffer)

	requestURL := fmt.Sprintf("%s://%s%s", "https", "flucky.cryptic.systems", "/temperatures")
	req, err := http.NewRequest("POST", requestURL, &buffer)
	if err != nil {
		return err
	}

	client := http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode < 200 || resp.StatusCode > 299 {
		return fmt.Errorf("Invalid HTTP-Statuscode - expected 200, got %d", resp.StatusCode)
	}

	return nil
}
