package main

import (
	"archive/zip"
	"fmt"
	"log"
	"time"

	client "github.com/influxdata/influxdb1-client/v2"
)

// Srcfile source file
type Srcfile struct {
	Filename string
	Filepath string
	Content  []byte
}

type Outfile struct {
	Content []byte
}

type FuelPricesConfig struct {
	RemoteURL      string
	RemoteFilename string
	XPathBase      string
	Pos            []string
	Types          []string
	TmpDir         string
	InfluxHost     string
	InfluxPort     int
	InfluxUser     string
	InfluxPass     string
	InfluxDB       string
}

type Price struct {
	Id     string
	Fuel   string
	Amount float64
}

var szip Srcfile
var sxml Srcfile
var ofile Outfile
var err error
var zipfile *zip.Reader

func main() {

	var fpc FuelPricesConfig
	GetConfig("common.ini", &fpc)

	sxml.Filename = fpc.RemoteFilename
	sxml.Filepath = fmt.Sprintf("%s/%s", fpc.TmpDir, sxml.Filename)

	httpClient, err := client.NewHTTPClient(client.HTTPConfig{
		Addr:     fmt.Sprintf("http://%s:%d", fpc.InfluxHost, fpc.InfluxPort),
		Username: fpc.InfluxUser,
		Password: fpc.InfluxPass,
	})

	bp, err := client.NewBatchPoints(client.BatchPointsConfig{
		Database: fpc.InfluxDB,
	})

	err = DownloadFile(fpc.RemoteURL)
	if err != nil {
		log.Fatal("Unable to download file")
	}

	err = ExtractZip()
	if err != nil {
		log.Fatal("Unable extract file")
	}

	var prices *[]Price
	var now = time.Now()

	GetPrices(&prices, fpc.Pos, fpc.Types, fpc.XPathBase)

	for _, p := range *prices {

		tags := map[string]string{"pdv": p.Id, "fuel": p.Fuel}
		fields := map[string]interface{}{"value": p.Amount}

		point, _ := client.NewPoint(
			"fuel_price",
			tags,
			fields,
			now,
		)

		bp.AddPoint(point)
		err = httpClient.Write(bp)
		HandleError(err)
	}

}
