package GmWeb

import (
	log "Server-Core/Server/Base/Log"
	service "Server-Core/Server/Base/Service"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"strconv"
)

type Payload struct {
	Msg_id   int    `json:"msg_id"`
	Msg_body string `json:"msg_body"`
}

func Create(port int) {
	http.HandleFunc("/gmApi/cmd", func(w http.ResponseWriter, r *http.Request) {
		// 设置CORS头
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

		if r.Method != http.MethodPost {
			http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
			return
		}

		body, err := ioutil.ReadAll(r.Body)
		if err != nil {
			http.Error(w, "Error reading request body", http.StatusInternalServerError)
			return
		}
		var payload Payload
		err = json.Unmarshal(body, &payload)
		if err != nil {
			http.Error(w, "Error unmarshalling JSON", http.StatusInternalServerError)
			return
		}
		log.Info("http analy struct message:%v", payload)

		ret, err := service.Call("logicMgr", "GMOnHandle", payload.Msg_id, payload.Msg_body)
		if err != nil {
			log.Error(err.Error(), nil)
			return
		}

		log.Info("http send message:%s", ret[0])
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(ret[0]) // 作为示例，我们将接收到的payload返回给客户端
	})

	log.Info("Starting GMWeb server at port:%d", port)
	go http.ListenAndServe(":"+strconv.Itoa(port), nil)

}
