package cvui

/*
#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>
*/
import "C"
import (
	"encoding/json"
	"netease_control_center/globals"
	"netease_control_center/interfaces/http"
	"netease_control_center/interfaces/log"
	"time"
	"unsafe"
)

func Init() {
	log.Println(log.DebugLog, "Begin init skin!")
	C.SkinInit()
	log.Println(log.DebugLog, "Init skin end!")
}

func GetSkinRes(key string) (path string) {
	jump := time.Now()
	defer func() {
		log.Println(log.DebugLog, "Get skin key:", key, " val:", path, " coast time:", time.Now().Sub(jump))
	}()

	ckey := C.CString(key)
	if uintptr(unsafe.Pointer(ckey)) != uintptr(0) {
		cpath := C.GetSkinsResource((*C.char)(unsafe.Pointer(ckey)), (*C.int)(unsafe.Pointer(uintptr(0))), (*C.int)(unsafe.Pointer(uintptr(0))), (**C.char)(unsafe.Pointer(uintptr(0))))
		gopath := C.GoString(cpath)
		if uintptr(unsafe.Pointer(cpath)) != uintptr(0) {
			C.free(unsafe.Pointer(cpath))
		}
		C.free(unsafe.Pointer(ckey))
		return gopath
	}

	return ""
}

func UpdateRes(jsonStr string) {
	cjsonstring := C.CString(jsonStr)
	if uintptr(unsafe.Pointer(cjsonstring)) != uintptr(0) {
		log.Println(log.DebugLog, "Begin update res!")
		C.SkinUpgrade(cjsonstring)
		C.free(unsafe.Pointer(cjsonstring))
	}
}

func UpdateResFromServer() {
	log.Println(log.DebugLog, "Begin to update res from server!")
	var req http.HttpReqHotfix
	var rsp http.HttpRspHotfix
	req.CurVersion = *globals.GitTag
	req.OsType = 0

	if code, _, err := http.HttpPostAuto(req, &rsp); globals.ErrCode(code) == globals.ERR_SUCCESS && err == nil {
		if data, err2 := json.Marshal(rsp); err2 == nil {
			UpdateRes(string(data))
		} else {
			log.Println(log.DebugLog, "Json marshal error:", err2)
		}
	} else {
		log.Println(log.DebugLog, "Update res error!", code, err)
	}
}
