package main

import (
	"fmt"
	"log"
	"net/url"
	"os"
	"os/exec"
	"time"

	"github.com/gorilla/websocket"
)

type websocketClientManager struct {
	conn        *websocket.Conn
	addr        *string
	path        string
	Userinfo    interface{}
	sendMsgChan chan string
	recvMsgChan chan string
	isAlive     bool
	timeout     int
	wtype       string
	user        string
	password    string
	room        string
}

// 构造函数
func NewWsClientManager(addrIp, addrPort, path string, timeout int, wtype string, password string, room string) *websocketClientManager {
	addrString := addrIp + ":" + addrPort
	var sendChan = make(chan string, 10)
	var recvChan = make(chan string, 10)
	var conn *websocket.Conn
	//获取本机电脑名
	usertemp, _ := os.Hostname()
	user := usertemp

	return &websocketClientManager{
		addr:        &addrString,
		path:        path,
		conn:        conn,
		sendMsgChan: sendChan,
		recvMsgChan: recvChan,
		isAlive:     false,
		timeout:     timeout,
		wtype:       wtype,
		user:        user,
		password:    password,
		room:        room,
	}
}

// 链接服务端
func (this *websocketClientManager) dail(wtype string, user string, password string, room string) {
	var err error

	u := url.URL{Scheme: "wss", Host: *this.addr, Path: this.path, ForceQuery: true, RawQuery: "user=" + user + "&password=" + password + "&room=" + room}
	log.Printf("connecting to %s", u.String())
	this.conn, _, err = websocket.DefaultDialer.Dial(u.String(), nil)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
		return
	}
	this.isAlive = true
	log.Printf("connecting to %s 链接成功！！！", u.String())
	//主动向服务端发送断开连接消息
	this.conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(4001, "close"), time.Now().Add(time.Second))
	ShutDownEXE()
}

func ShutDownEXE() {
	fmt.Println("关闭主机")
	arg := []string{"-s", "-t", "0"}
	cmd := exec.Command("shutdown", arg...)
	_, err := cmd.CombinedOutput()
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
}
func main() {
	wss := "wss"
	password := "efghijk"
	room := "admin"
	t := NewWsClientManager("www.360xyz.cn", "443", "/service/wss", 10, wss, password, room)
	t.dail(t.wtype, t.user, t.password, t.room)
}
