package chess

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"math/rand"
	"net/http"
	"time"

	"mongo.games.com/goserver/core/logger"
	"mongo.games.com/goserver/core/netlib"

	"mongo.games.com/game/common"
	rule "mongo.games.com/game/gamerule/chess"
	"mongo.games.com/game/proto"
	proto_chesstitians "mongo.games.com/game/protocol/chesstitians"
	"mongo.games.com/game/robot/base"
)

type StockfishReq struct {
	Fen        string `json:"fen"`
	Time       int    `json:"time"`
	SkillLevel int    `json:"skillLevel"`
}

type StockfishResp struct {
	Fen      string
	Time     int64
	Bestmove string
	Ponder   string
	Error    int
}

func Testjson() {
	// test 发送http请求
	client := &http.Client{}

	// 创建HTTP请求
	req, err := http.NewRequest("GET", "http://127.0.0.1:23988/chess/jsontest", nil)
	if err != nil {
		panic(err)
	}

	// 发送HTTP请求
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	// 处理HTTP响应
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}
	//fmt.Println(string(body))
	logger.Logger.Infof("@jsonTest %s", string(body))
	var stockfishResp StockfishResp
	err = json.Unmarshal(body, &stockfishResp)
	if err != nil {
		panic(err)
	}
	logger.Logger.Infof("@bestmove=%s,ponder=%s", stockfishResp.Bestmove, stockfishResp.Ponder)
}

func UCIPost(fen string, timeScore int) StockfishResp {
	var stockfishResp = StockfishResp{
		Error: 1,
	}
	client := &http.Client{Timeout: time.Second * 5}
	reqBody := StockfishReq{
		Fen:  fen,
		Time: timeScore,
	}
	reqJsonString, err := json.Marshal(reqBody)
	if err != nil {
		stockfishResp.Error = 2
		logger.Logger.Errorf("@UCIPost %v %v", stockfishResp, err.Error())
		return stockfishResp
	}
	logger.Logger.Infof("@UCIPost %v", string(reqJsonString))
	// 创建HTTP请求
	req, err := http.NewRequest("POST", common.CustomConfig.GetString("UCIURL"), bytes.NewBuffer(reqJsonString))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Content-Type", "application/json")
	// 发送HTTP请求
	resp, err := client.Do(req)
	if err != nil {
		stockfishResp.Error = 3
		logger.Logger.Errorf("@UCIPost %v %v", stockfishResp, err.Error())
		return stockfishResp
	}
	// 处理HTTP响应
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		stockfishResp.Error = 4
		logger.Logger.Errorf("@UCIPost %v %v", stockfishResp, err.Error())
		return stockfishResp
	}
	logger.Logger.Infof("@jsonTest %s", string(body))
	err = json.Unmarshal(body, &stockfishResp)
	if err != nil {
		stockfishResp.Error = 5
		logger.Logger.Errorf("@UCIPost %v %v", stockfishResp, err.Error())
		return stockfishResp
	}
	stockfishResp.Error = 0
	logger.Logger.Infof("@bestmove=%s,ponder=%s", stockfishResp.Bestmove, stockfishResp.Ponder)
	return stockfishResp
}

func MakrukPost(fen string, timeScore int) StockfishResp {
	var stockfishResp = StockfishResp{
		Error: 1,
	}
	client := &http.Client{Timeout: time.Second * 5}
	reqBody := StockfishReq{
		Fen:  fen,
		Time: timeScore,
	}
	reqJsonString, err := json.Marshal(reqBody)
	if err != nil {
		stockfishResp.Error = 2
		logger.Logger.Errorf("@UCIPost %v %v", stockfishResp, err.Error())
		return stockfishResp
	}
	logger.Logger.Infof("@UCIPost %v", string(reqJsonString))
	// 创建HTTP请求
	req, err := http.NewRequest("POST", common.CustomConfig.GetString("MakrukURL"), bytes.NewBuffer(reqJsonString))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Content-Type", "application/json")
	// 发送HTTP请求
	resp, err := client.Do(req)
	if err != nil {
		stockfishResp.Error = 3
		logger.Logger.Errorf("@UCIPost %v %v", stockfishResp, err.Error())
		return stockfishResp
	}
	// 处理HTTP响应
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		stockfishResp.Error = 4
		logger.Logger.Errorf("@UCIPost %v %v", stockfishResp, err.Error())
		return stockfishResp
	}
	logger.Logger.Infof("@jsonTest %s", string(body))
	err = json.Unmarshal(body, &stockfishResp)
	if err != nil {
		stockfishResp.Error = 5
		logger.Logger.Errorf("@UCIPost %v %v", stockfishResp, err.Error())
		return stockfishResp
	}
	stockfishResp.Error = 0
	logger.Logger.Infof("@bestmove=%s,ponder=%s", stockfishResp.Bestmove, stockfishResp.Ponder)
	return stockfishResp
}

func CambodianPost(fen string, timeScore int, skillLevel int) StockfishResp {
	var stockfishResp = StockfishResp{
		Error: 1,
	}
	client := &http.Client{Timeout: time.Second * 5}
	reqBody := StockfishReq{
		Fen:        fen,
		Time:       timeScore,
		SkillLevel: skillLevel,
	}
	reqJsonString, err := json.Marshal(reqBody)
	if err != nil {
		stockfishResp.Error = 2
		logger.Logger.Errorf("@UCIPost %v %v", stockfishResp, err.Error())
		return stockfishResp
	}
	logger.Logger.Infof("@UCIPost %v", string(reqJsonString))
	// 创建HTTP请求
	req, err := http.NewRequest("POST", common.CustomConfig.GetString("CambodianURL"), bytes.NewBuffer(reqJsonString))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Content-Type", "application/json")
	// 发送HTTP请求
	resp, err := client.Do(req)
	if err != nil {
		stockfishResp.Error = 3
		logger.Logger.Errorf("@UCIPost %v %v", stockfishResp, err.Error())
		return stockfishResp
	}
	// 处理HTTP响应
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		stockfishResp.Error = 4
		logger.Logger.Errorf("@UCIPost %v %v", stockfishResp, err.Error())
		return stockfishResp
	}
	logger.Logger.Infof("@jsonTest %s", string(body))
	err = json.Unmarshal(body, &stockfishResp)
	if err != nil {
		stockfishResp.Error = 5
		logger.Logger.Errorf("@UCIPost %v %v", stockfishResp, err.Error())
		return stockfishResp
	}
	stockfishResp.Error = 0
	logger.Logger.Infof("@bestmove=%s,ponder=%s", stockfishResp.Bestmove, stockfishResp.Ponder)
	return stockfishResp
}

func AiRandom(s *netlib.Session) {
	if scene, ok := base.GetScene(s).(*ChesstitiansScene); ok {
		p := scene.GetMe(s)
		if me, ok2 := p.(*ChesstitiansPlayer); ok2 && me != ChesstitiansNilPlayer {
			if scene.State == int32(rule.SceneStatePlayerOp) {
				if me.IsBlack == 1 && scene.GetAct() == "b" || me.IsBlack != 1 && scene.GetAct() == "w" {
					// 轮到当前行棋方
					chess := scene.chess
					fen := chess.GenFen()
					logger.Logger.Infof("fen: %s", fen)

					// 随机走一步

					logger.Logger.Info("随机走一步")
					// 随机走一步
					ms := chess.GetMoveAllPositions(me.IsBlack != 1)
					if len(ms) > 0 {
						m := ms[rand.Intn(len(ms))]
						packOp := &proto_chesstitians.SCChesstitiansPlayerOp{
							OpCode:  proto.Int32(rule.PlayerOpPlay),
							OpParam: []int64{int64(m[0].Index), int64(m[1].Index)},
						}
						base.DelaySendSecond(s, int(proto_chesstitians.ChesstitiansPacketID_PACKET_CSChesstitiansPlayerOp), packOp, []int{1, 2}...)
						logger.Logger.Infof("CSChesstitiansPlayerOp random %v", packOp.String())
					} else {
						logger.Logger.Errorf("随机一步失败")
					}
				}
			}
		}
	}
}
