package public

import (
	"encoding/json"
	"net"
	"net/http"
	"io"
	"bytes"
	"bufio"
)

func SendDaemon(v interface{})[]byte{
	return SendMsg(LocalDaemon,v)
}
// func SendDaemonGuiExec(s stirng)
// 			SendDaemon()
func SendDaemonExec(s string){
		   SendDaemon(GJexecUserCmd(s))
}
func SendServerReport(s string)[]byte{
	return SendServer(GJreport(s,""))
}
func SendServerExec(s string)[]byte{
	return SendServer(GJexec(s))
}

func SendServerError(s string)[]byte{
	return SendServer(GJerror(&s))
}
// send to server
func SendServer(v interface{})[]byte{
	return SendMsg(ADServerDaemon,v)
}
// base
func SendMsg(you string ,v interface{})[]byte{

	textbyte,err := json.Marshal(v)
	if err !=nil {
		PrintLog("Json to String Error ",v,err)
	}

	conn, err := net.Dial("tcp", you)
	if err != nil {
		PrintLog("err = ", err)
	}

	//发送数据
	conn.Write(textbyte)
	PrintLog("SEND ",string(textbyte))
	bmsg,cerr:= bufio.NewReader(conn).ReadBytes(EndSign)
	var rec []byte
	if cerr != io.EOF {
		// 获取ip
		ip := GetConnIP(conn.RemoteAddr())

		// 获取消息类型
		msgtype := ParseJsonHead(bmsg)

		// 处理消息
		rec = DealMsgEnter(ip,msgtype,bmsg)
	}
	if err := conn.Close();err !=nil{
		PrintLog("Conn Close ",err)
	}
	return rec
}

// 发送 到 微信机器人
func SendWX(Content string){
	
	w := []byte(`
	{
		 "msgtype": "text",
		 "text": {
			 "content": "`+Content+`"
		 }
	}`)
	http.Post(Link_WxworkBot,"application/json; charset=utf-8",bytes.NewBuffer(w))
}