package main

import (
	"log"
	"net"
	"os/exec"
	"pcmqtt/models"
	"strings"
	"syscall"
	"time"
	"unsafe"

	mqtt "github.com/eclipse/paho.mqtt.golang"
)

var windowsAlert = WindowsAlert{}
var mqttClient = models.MqttClient{}

func main() {
	mac := GetMac()
	mac = strings.TrimSpace(mac)
	mqttClient := models.MqttClient{
		Broker:        "tcp://192.168.0.254:1883",
		ClientId:      "pcmqtt-" + mac,
		Username:      mac,
		Password:      mac,
		Reconnecting:  false,
		Subscriptions: map[string]byte{"computer/control": 0},
	}
	mqttClient.Setup()
	mqttClient.Subscribe("computer/control", 0, func(client mqtt.Client, msg mqtt.Message) {
		message := string(msg.Payload())
		log.Println(message)
		if message == mqttClient.Username+":shutdown" {
			arg := []string{"-s", "-t", "0"}
			cmd := exec.Command("shutdown", arg...)
			cmd.CombinedOutput()
		} else {
			go func() {
				windowsAlert.ShowMessage("服务器提示", message)
			}()
		}
	})
	for {
	}
}
func GetMac() string {
	netInterfaces, err := net.Interfaces()
	if err != nil {
		return ""
	}
	for _, i2 := range netInterfaces {
		//fmt.Println(i2.Name)
		mac := i2.HardwareAddr
		//fmt.Println(mac)
		return mac.String()
	}
	return ""
}

type WindowsAlert struct {
}

func (ggg *WindowsAlert) StrPtr(s string) uintptr {
	utf16Ptr, _ := syscall.UTF16PtrFromString(s)
	return uintptr(unsafe.Pointer(utf16Ptr))
}
func (ggg *WindowsAlert) ShowMessage(title, text string) {
	user32dll, _ := syscall.LoadLibrary("user32.dll")
	user32 := syscall.NewLazyDLL("user32.dll")
	MessageBoxW := user32.NewProc("MessageBoxW")
	defer syscall.FreeLibrary(user32dll)
	MessageBoxW.Call(uintptr(0), ggg.StrPtr(text), ggg.StrPtr(title), uintptr(0))
	time.Sleep(time.Second * 3)
}
