package main

import (
	"bytes"
	"fmt"
	"io"
	"mongo.games.com/game/common"
	"mongo.games.com/game/model"
	"mongo.games.com/game/proto"
	"mongo.games.com/game/protocol/player"
	"mongo.games.com/game/webapi"
	"mongo.games.com/goserver/core/basic"
	"mongo.games.com/goserver/core/logger"
	"mongo.games.com/goserver/core/netlib"
	"mongo.games.com/goserver/core/task"
	"net/http"
	"strings"
	"time"
)

func init() {
	// 玩家透传
	//netlib.RegisterFactory(int(player.PlayerPacketID_PACKET_CS_WEBAPI_PLAYERPASS), netlib.PacketFactoryWrapper(func() interface{} {
	//	return &player.CSWebAPIPlayerPass{}
	//}))
	//netlib.RegisterHandler(int(player.PlayerPacketID_PACKET_CS_WEBAPI_PLAYERPASS), netlib.HandlerWrapper(func(s *netlib.Session, packetid int, pack interface{}) error {
	//	logger.Logger.Trace("receive CSWebAPIPlayerPass info==", pack)
	//	if msg, ok := pack.(*player.CSWebAPIPlayerPass); ok {
	//		var pdi = s.GetAttribute(common.ClientSessionAttribute_PlayerData)
	//		if pdi == nil {
	//			return nil
	//		}
	//		var playerData = pdi.(*model.PlayerData)
	//		opCode := player.OpResultCode_OPRC_Sucess
	//		errString := ""
	//		var err error
	//		t, done := task.NewMutexTask(nil, task.CallableWrapper(func(o *basic.Object) interface{} {
	//			errString, err = webapi.API_PlayerPass(playerData.SnId, playerData.Platform, playerData.Channel, playerData.BeUnderAgentCode, msg.GetApiName(), msg.GetParams(), common.GetAppId(), playerData.LogicLevels)
	//			if err != nil {
	//				logger.Logger.Errorf("API_PlayerPass error:%v api:%v params:%v", err, msg.GetApiName(), msg.GetParams())
	//				opCode = player.OpResultCode_OPRC_Error
	//				return nil
	//			}
	//			return err
	//		}), task.CompleteNotifyWrapper(func(data interface{}, t task.Task) {
	//			pack := &player.SCWebAPIPlayerPass{
	//				OpRetCode: opCode,
	//				ApiName:   msg.ApiName,
	//				CBData:    msg.CBData,
	//				Response:  proto.String(errString),
	//			}
	//			s.Send(int(player.PlayerPacketID_PACKET_SC_WEBAPI_PLAYERPASS), pack)
	//			logger.Logger.Trace("SCWebAPIPlayerPass:", pack)
	//		}), fmt.Sprintf("%v?%v", msg.GetApiName(), msg.GetParams()), "API_PlayerPass")
	//		if !done {
	//			t.Start()
	//		}
	//	}
	//	return nil
	//}))

	// 系统透传
	netlib.RegisterFactory(int(player.PlayerPacketID_PACKET_CS_WEBAPI_SYSTEMPASS), netlib.PacketFactoryWrapper(func() interface{} {
		return &player.CSWebAPISystemPass{}
	}))
	netlib.RegisterHandler(int(player.PlayerPacketID_PACKET_CS_WEBAPI_SYSTEMPASS), netlib.HandlerWrapper(func(s *netlib.Session, packetid int, pack interface{}) error {
		logger.Logger.Trace("receive CSWebAPIPlayerPass info==", pack)
		if msg, ok := pack.(*player.CSWebAPISystemPass); ok {
			opCode := player.OpResultCode_OPRC_Sucess
			errString := ""
			var err error
			t, done := task.NewMutexTask(nil, task.CallableWrapper(func(o *basic.Object) interface{} {
				errString, err = webapi.API_SystemPass(msg.GetApiName(), msg.GetParams(), msg.GetCBData(), common.GetAppId())
				if err != nil {
					logger.Logger.Errorf("API_SystemPass error:%v apiname=%v params=%v", err, msg.GetApiName(), msg.GetParams())
					opCode = player.OpResultCode_OPRC_Error
					return nil
				}
				return err
			}), task.CompleteNotifyWrapper(func(data interface{}, t task.Task) {
				pack := &player.SCWebAPISystemPass{
					OpRetCode: opCode,
					ApiName:   msg.ApiName,
					CBData:    msg.CBData,
					Response:  proto.String(errString),
				}
				s.Send(int(player.PlayerPacketID_PACKET_SC_WEBAPI_SYSTEMPASS), pack)
				logger.Logger.Trace("SCWebAPISystemPass:", pack)
			}), fmt.Sprintf("%v?%v", msg.GetApiName(), msg.GetParams()), "API_SystemPass")
			if !done {
				t.Start()
			}
		}
		return nil
	}))

	// http转发
	netlib.Register(int(player.PlayerPacketID_PACKET_CS_HTTP_PASS), player.CSHttpPass{}, CSHttpPass)
}

const HTTPPASSTimeout = time.Second * 10

func CSHttpPass(s *netlib.Session, packetid int, pack interface{}) error {
	logger.Logger.Trace("receive CSHttpPass ", pack)
	msg, ok := pack.(*player.CSHttpPass)
	if !ok {
		return nil
	}

	switch msg.ServerType {
	case 1: // 语音
		opCode := player.OpResultCode_OPRC_Sucess
		errString := ""
		var err error
		var req *http.Request
		var resp *http.Response
		t, done := task.NewMutexTask(nil, task.CallableWrapper(func(o *basic.Object) interface{} {
			req, err = http.NewRequest(strings.ToUpper(msg.GetMethod()), fmt.Sprintf("%v%v", model.GameParamData.AgoraAddress, msg.ApiName), bytes.NewBuffer([]byte(msg.GetParams())))
			if err != nil {
				logger.Errorf("CSHttpPass NewRequest error:%v method=%v apiname=%v params=%v", err, msg.GetMethod(), msg.GetApiName(), msg.GetParams())
				return nil
			}
			cli := http.Client{}
			cli.Timeout = HTTPPASSTimeout
			resp, err = cli.Do(req)
			if err != nil {
				logger.Errorf("CSHttpPass Do error:%v method=%v apiname=%v params=%v", err, msg.GetMethod(), msg.GetApiName(), msg.GetParams())
				return nil
			}
			return nil
		}), task.CompleteNotifyWrapper(func(data interface{}, t task.Task) {
			if err != nil {
				logger.Logger.Errorf("CSHttpPass error:%v method=%v apiname=%v params=%v", err, msg.GetMethod(), msg.GetApiName(), msg.GetParams())
				opCode = player.OpResultCode_OPRC_Error
			} else {
				defer resp.Body.Close()
				respBytes, err := io.ReadAll(resp.Body)
				if err != nil {
					logger.Logger.Errorf("CSHttpPass ReadAll error:%v method=%v apiname=%v params=%v", err, msg.GetMethod(), msg.GetApiName(), msg.GetParams())
					opCode = player.OpResultCode_OPRC_Error
				} else {
					errString = string(respBytes)
				}
			}

			pack := &player.SCHttpPass{
				OpRetCode: opCode,
				ApiName:   msg.ApiName,
				CBData:    msg.CBData,
				Response:  proto.String(errString),
			}
			s.Send(int(player.PlayerPacketID_PACKET_SC_HTTP_PASS), pack)
			logger.Logger.Trace("CSHttpPass:", pack)
		}), fmt.Sprintf("%v?%v", msg.GetApiName(), msg.GetParams()), "CSHttpPass")
		if !done {
			t.Start()
		}

	default:
		return nil
	}
	return nil
}
