package wifi

/*
#cgo CFLAGS: -I${SRCDIR}/../../../../../../../staging_dir/target/usr/include
#cgo LDFLAGS:-L${SRCDIR}/../../../../../../../staging_dir/target/lib -luvdbus -lwifimg -lpthread -lc -lcrypto -lcjson -lsqlite3 -ls2json  -L${SRCDIR}/../../../../../../../staging_dir/target/usr/lib/libiconv-full/lib  -liconv
#include <stdlib.h>
#include <stdio.h>
#include "wifi_intf.h"

extern void GoWifiEventHd(int event, int label);
void wifi_event_handle(tWIFI_EVENT wifi_event, void *buf, int event_label) {
	GoWifiEventHd((int) wifi_event, (int) event_label);
}

int remove_allnet(aw_wifi_interface_t *wifi) {
	return wifi->remove_all_networks();
}

int connect_ap(aw_wifi_interface_t *wifi, char *ssid, char *pass, int label) {
	printf("CONNECT: SSID:%s, PASS:%s \n", ssid, pass);
	return wifi->connect_ap((const char *) ssid, (const char *)pass, label);
}
*/
import "C"
import (
	"netease_control_center/interfaces/log"
	"time"
	"unsafe"
)

const (
	EVENT_LABEL   = 123
	WIFI_SSID     = "dundun_2g"
	WIFI_PASSWORD = "dundundun"
)

var (
	WifiInterface *C.aw_wifi_interface_t
	cWifiEventHd  = C.tWifi_event_callback(C.wifi_event_handle)
)

func WaitWifiReady() {
	for {
		wifistatus := C.aw_wifi_get_wifi_state()
		if int(wifistatus) == int(C.WIFIMG_WIFI_BUSING) {
			time.Sleep(time.Millisecond * time.Duration(2000))
			log.Println(log.WarningLog, "Wifi is busy, wait 2000 ms")
		} else {
			log.Println(log.DebugLog, "Wifi not busy, continue")
			break
		}
	}
}

func Connect(wifi_ssid string, wifi_pass string) {
	log.Println(log.DebugLog, "Begin to init wifi in go")
	WifiInterface = C.aw_wifi_on(cWifiEventHd, C.int(EVENT_LABEL))
	WaitWifiReady()

	ssid := C.CString(wifi_ssid)
	pass := C.CString(wifi_pass)
	labe := C.int(EVENT_LABEL + 1)
	C.connect_ap(WifiInterface, ssid, pass, labe)
	C.free(unsafe.Pointer(ssid))
	C.free(unsafe.Pointer(pass))

	log.Println(log.DebugLog, "Set wifi ok")
	WaitWifiReady()
}
