package public

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

func SendDaemon(v interface{})[]byte{
	return SendMsg(LocalDaemon,v)
}

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 SendServerGUIExec(s string){
	SendServer(GJexecGUI(s))
}
func SendServerError(err error)[]byte{
	return SendServer(GJerror(err))
}
func SendServerErrorf(f string, a ...interface{}) []byte {
	return SendServer(GJerror(fmt.Errorf(f,a ...)))
}

// 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 {
		PntError("Json to String Error ",v,err)
	}

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

	//发送数据
	conn.Write(textbyte)
	PntSend(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{
		PntError("Conn Close ",err)
	}
	return rec
}

// 发送 到 微信机器人
func SendWX(Content string){

	// Content不支持发送Json，

	w := []byte(`
	{
		 "msgtype": "text",
		 "text": {
			 "content": "`+Content+`"
		 }
	}`)
	http.Post(Link_WxworkBot,"application/json; charset=utf-8",bytes.NewBuffer(w))
}