package android

import (
	"fmt"
	"net"
    "database/sql"
    "time"
    "pkg/app"
    "errors"

    _ "github.com/mattn/go-sqlite3"
    "github.com/gin-gonic/gin"
)

//获取本设备的mac地址
func getMacAddress() (macAddress string) {
    netInterfaces, err := net.Interfaces()
    if err != nil {
        fmt.Printf("fail to get net interfaces: %v", err)
        return macAddress
    }

	for _, netInterface := range netInterfaces {
        if ( netInterface.Name == "WLAN" ) {
            macAddress := netInterface.HardwareAddr
            return macAddress.String()
        }
    }
    return macAddress
}

//获取本设备的IP地址
func getIpAddress() (addr string, err error) {
	var (
		ief      *net.Interface
		addrs    []net.Addr
		ipv4Addr net.IP
	)
	if ief, err = net.InterfaceByName("WLAN"); err != nil {
		return
	}
	if addrs, err = ief.Addrs(); err != nil {
		return
	}
	for _, addr := range addrs {
		if ipv4Addr = addr.(*net.IPNet).IP.To4(); ipv4Addr != nil {
			break
		}
	}
	if ipv4Addr == nil {
		return "", errors.New(fmt.Sprintf("interface WLAN don't have an ipv4 address\n"))
	}
	return ipv4Addr.String(), nil
}

//向服务器发送本设备的mac地址和IP地址
func sendAddress(c *gin.Context) {
    appG := app.Gin{C: c}
    now := time.Now()
    hour := now.Hour()
	minute := now.Minute()
	t := hour*100 + minute
	macAddress := getMacAddress()
    ipAddress, err := getIpAddress()
    if err != nil {
		fmt.Println(err)
	}
    db, err := sql.Open("sqlite3", "info.db")
	if err != nil {
		fmt.Println(err)
	}
	defer db.Close()
    rows, err := db.Query(`select macAddress from Endpoint where macAddress = ?;`, macAddress)
    defer rows.Close()
    var MacAddress string
    rows.Next()
    rows.Scan(&MacAddress)
    if MacAddress == "" {
        db.Exec(`insert into Endpoint values (?,?,?,?);`, macAddress, ipAddress, 0, t)
    } else {
        db.Exec(`update Endpoint set ipAddress = ? where macAddress = ?;`, ipAddress, macAddress)
        db.Exec(`update Endpoint set isOnLine = ? where macAddress = ?;`, t, macAddress)
    }
	appG.Response(http.StatusOK, "true", null)
}

func mediaPipe(c *gin.Context) {
    appG := app.Gin{C: c}
    //这里将视频流转化为自然语言
    data := 
    appG.Response(http.StatusOK, "true", data)
}