package file_cache

import (
	"encoding/json"
	"github.com/influxdata/influxdb/client/v2"
	"github.com/json-iterator/go"
	"strconv"
	"time"
	"unsafe"
)

type CachePoint struct {
	Name   string                 `json:"name"`
	Tags   map[string]string      `json:"tags"`
	Fields map[string]interface{} `json:"fields"`
	Time   time.Time              `json:"time"`
}

func NewPoint(point *client.Point) CachePoint {
	cp := CachePoint{}
	cp.Name = point.Name()
	cp.Time = point.Time()
	cp.Fields, _ = point.Fields()
	cp.Tags = point.Tags()
	return cp
}

func CreateCachePoint(data string) *CachePoint {
	cp := CachePoint{}
	jsoniter.Unmarshal([]byte(data), &cp)

	if v, ok := cp.Fields["system_load_average"]; ok {
		switch v.(type) {
		case float64:
			break
		case int:
			cp.Fields["system_load_average"],_ = strconv.ParseFloat(strconv.Itoa(v.(int)), 64)
			break
		case int64:
			cp.Fields["system_load_average"],_ = strconv.ParseFloat(strconv.FormatInt(v.(int64),10), 64)
			break

		}
	}
	return &cp
}

func init() {
	decodeNumberAsInt64IfPossible := func(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
		switch iter.WhatIsNext() {
		case jsoniter.NumberValue:
			var number json.Number
			iter.ReadVal(&number)
			i, err := strconv.ParseInt(string(number), 10, 64)
			if err == nil {
				*(*interface{})(ptr) = i
				return
			}
			f, err := strconv.ParseFloat(string(number), 64)
			if err == nil {
				*(*interface{})(ptr) = f
				return
			}
			// Not much we can do here.
		default:
			*(*interface{})(ptr) = iter.Read()
		}
	}
	jsoniter.RegisterTypeDecoderFunc("interface {}", decodeNumberAsInt64IfPossible)
}
