package wifi

/*
#cgo LDFLAGS: -lbsa -luvdbus -lwifimg -lpthread -ldl -lstdc++ -lrt -lm -lc -lz -lsoftap
#include <stdio.h>
#include <stdlib.h>
//#include <bluetooth_socket.h>
#include "softap.h"
*/
import "C"
import (
	"netease_control_center/globals"
	"netease_control_center/interfaces/log"
	"sync"
	"unsafe"
)

var lock sync.Mutex

type APSTATUS int

const (
	APSTATUS_UNKNOW APSTATUS = iota
	APSTATUS_ON
	APSTATUS_OFF
)

var (
	curApStatus = APSTATUS_OFF
)

func CheckAPStatus() {
	//status := C.nSoftapstarted()
	//log.Println(log.DebugLog, "AP is start? ", status)
}

func GetAPstatus() (st APSTATUS) {
	defer func() {
		log.Println(log.DebugLog, "APSTATUS FROM SQL: ", st)
	}()

	return curApStatus

	//if err := storage.Config_get(globals.MODULE_CONTROLLER, globals.SQL_KEY_APSTATUS, &st); err == nil {
	//	return st
	//} else {
	//	return APSTATUS_OFF
	//}
}

func SetAPstatus(st APSTATUS) error {
	curApStatus = st
	return nil

	//if err := storage.Config_set(globals.MODULE_CONTROLLER, globals.SQL_KEY_APSTATUS, st); err != nil {
	//	log.Println(log.ErrorLog, "Set ap status error:", err)
	//	return err
	//} else {
	//	return nil
	//}
}

func StartAP() {
	log.Println(log.DebugLog, "Begin to get ap lock! start")
	lock.Lock()
	defer lock.Unlock()
	log.Println(log.DebugLog, "Get ap lock success! start")

	if GetAPstatus() != APSTATUS_ON {
		log.Println(log.DebugLog, "Start AP!")
		ssid := C.CString(globals.BTNAME)
		pass := C.CString("")
		log.Println(log.DebugLog, "AP id:", ssid, " pass:", pass)
		C.nSoftapUp(ssid, pass)
		C.free(unsafe.Pointer(ssid))
		C.free(unsafe.Pointer(pass))
		SetAPstatus(APSTATUS_ON)
		log.Println(log.DebugLog, "Start ap success!")

		globals.ClearWifiStatus()
	}
	log.Println(log.DebugLog, "Start ap exit!")
}

func ShutDownAP() {
	log.Println(log.DebugLog, "Begin to get ap lock! stop")
	lock.Lock()
	defer lock.Unlock()
	log.Println(log.DebugLog, "Get ap lock success! stop")

	if GetAPstatus() != APSTATUS_OFF {
		globals.ClearWifiStatus()

		log.Println(log.DebugLog, "Shut down ap!")
		C.nSoftapDown()
		SetAPstatus(APSTATUS_OFF)
		log.Println(log.DebugLog, "Shut down ap success!")
	}

	log.Println(log.DebugLog, "Down ap exit!")
}

func TestAP() {
	CheckAPStatus()
	if GetAPstatus() != APSTATUS_ON {
		StartAP()
	} else {
		ShutDownAP()
	}
}
