package eventPoint

/*
#cgo CFLAGS: -fvisibility=hidden
#cgo LDFLAGS:-lpthread -ldl -lstdc++ -lrt -lm -lc -lz -luv -lcjson -luvdbus -lcurl -lcrypto -ldbus-1 -lsqlite3 -ls2json -lquickmail -luuid -lcutils -lconfig
#include <stdio.h>
#include <stdlib.h>
#include <uvdbus/skins.h>
#include <uvdbus/libuv_dbus.h>
#include <uvdbus/log.h>
*/
import "C"
import (
	"encoding/json"
	"netease_control_center/interfaces/http"
	"netease_control_center/interfaces/log"
	"sync"
	"time"
	"unsafe"
)

var (
	initCepOnce = sync.Once{}
)

type EpOs int8

const (
	EpOs_Device EpOs = 2
	EpOs_Server EpOs = 0
	EpOs_App    EpOs = 1
)

var (
	//osSource = map[string]EpOs{}
	osSource = sync.Map{}
)

type EventPoint struct {
	Base   http.HttpReqbase       `json:"base"`
	Params map[string]interface{} `json:"params"`
}

func SetEpOsSouce(eventId string, source EpOs) {
	osSource.Store(eventId, source)
}

func EpRecord(eventId string, args map[string]interface{}) {
	defer func() {
		if err := recover(); err != nil {
			log.Println(log.ErrorLog, err)
		}
	}()

	var tmp EventPoint
	tmp.Base = http.Reqbase
	args["event"] = eventId
	args["timestamp"] = time.Now().UnixNano() / 1e6
	tmp.Params = args

	if val, ok := osSource.Load(eventId); ok {
		if _, ok2 := args[eventId]; ok2 == false {
			args["sourceos"] = val
		}
	}

	if data, err := json.Marshal(tmp); err == nil {
		CWriteEp(string(data) + "\n")
		log.Println(log.WarningLog, "EventPoint:", string(data))
	}
}

func CEpInit() {
	log.Println(log.DebugLog, "Init C ep log!")
	deviceid := C.CString("1234")
	C.SysPointMarkInit(deviceid, -1, -1)
	C.free(unsafe.Pointer(deviceid))
}

func CWriteEp(data string) {
	initCepOnce.Do(CEpInit)
	//jump := time.Now()
	//defer func() {
	//	log.Println(log.DebugLog, "Write c ep coast:", time.Now().Sub(jump))
	//}()
	cdata := C.CString(data)

	if uintptr(unsafe.Pointer(cdata)) != uintptr(0) {
		C.SysPointMark(cdata)
		C.free(unsafe.Pointer(cdata))
	}
}
