package main

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

// WorldCreateRequest 定义了创建世界时发送的请求体的结构体
type WorldCreateRequest struct {
	Auth     string `json:"auth"`
	Name     string `json:"name"`
	BgInfo   string `json:"BgInfo,omitempty"`
	UserInfo string `json:"userInfo"`
}

// WorldCreateResponse 定义了创建世界时接受的响应体的结构体
type WorldCreateResponse struct {
	Code    int    `json:"code"`
	ISLIUid string `json:"ISLIUid"`
	WObj    string `json:"WObj"`
	ISLIU   string `json:"ISLIU"`
}

// CreateWorld 是向指定的地址发送创建世界请求的函数
func CreateWorld(url string, request WorldCreateRequest) (*WorldCreateResponse, error) {
	// 将请求体编码为 JSON
	requestBody, err := json.Marshal(request)
	if err != nil {
		return nil, fmt.Errorf("failed to encode request body: %w", err)
	}

	// 创建 POST 请求
	resp, err := http.Post(url, "application/json", bytes.NewBuffer(requestBody))
	if err != nil {
		return nil, fmt.Errorf("failed to send request: %w", err)
	}
	defer resp.Body.Close()

	// 读取和解码响应体
	var response WorldCreateResponse
	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("failed to read response body: %w", err)
	}

	err = json.Unmarshal(respBody, &response)
	if err != nil {
		return nil, fmt.Errorf("failed to decode response body: %w", err)
	}

	return &response, nil
}

func main() {
	// 示例请求数据
	requestData := WorldCreateRequest{
		Auth:     "your_auth_signature",
		Name:     "情圣日记",
		BgInfo:   "我是罗翔爱徒",
		UserInfo: `{"name":"张三","bk":"罗翔爱徒"}`,
	}

	// 发送请求并接收响应
	response, err := CreateWorld("http://52.83.116.11:13679/world/new", requestData)
	if err != nil {
		fmt.Println("Error creating world:", err)
		return
	}

	// 打印响应结果
	fmt.Println("Response Code:", response.Code)
	fmt.Println("ISLIUid:", response.ISLIUid)
	fmt.Println("WObj:", response.WObj)
	fmt.Println("ISLIU:", response.ISLIU)
}
