package temperature

import (
	"fmt"
	"strconv"
	"time"

	influx "github.com/influxdata/influxdb/client/v2"
)

// Writer is used to write out measurements
type Writer interface {
	Write(Measurement) error
}

type influxWriter struct {
	locations map[int]string
	db        string
	client    influx.Client
}

func (i influxWriter) Write(measurement Measurement) error {
	bp, err := influx.NewBatchPoints(influx.BatchPointsConfig{
		Database:  i.db,
		Precision: "s",
	})
	if err != nil {
		fmt.Println("Could not log temperature")
		fmt.Println(err)
		return err
	}
	var tags = map[string]string{}
	if val, ok := i.locations[measurement.ID]; ok {
		tags["location"] = val

	} else {
		tags["location"] = "id:" + strconv.FormatInt(int64(measurement.ID), 10)
	}
	fields := map[string]interface{}{
		"temperature": measurement.Temperature,
	}

	pt, err := influx.NewPoint("temperature", tags, fields, time.Now())

	if err != nil {
		fmt.Println("Could not log temperature")
		fmt.Println(err)
		return err
	}
	bp.AddPoint(pt)
	err = i.client.Write(bp)

	if err != nil {
		fmt.Println("Could not log temperature")
		fmt.Println(err)
		return err
	}
	fmt.Println("Wrote measurement successfully")
	return nil
}

// NewInfluxWriter creates an influxdb writer
func NewInfluxWriter(db string, host string, username string, password string, locations map[int]string) (Writer, error) {
	client, err := influx.NewHTTPClient(influx.HTTPConfig{
		Addr:     host,
		Username: username,
		Password: password,
	})
	if err != nil {
		return nil, err
	}
	return &influxWriter{db: db, client: client, locations: locations}, nil

}