package gameServerMgr

import (
	"encoding/json"
	"errors"
	"fmt"
	"time"

	"Framework/goroutineMgr"
	. "Framework/managecenterModel"
	"goutil/logUtil"
	"goutil/webUtil"
)

const SYSCONF_URL_SUFFIX string = "/API/SysConfig.ashx"

var (
	mSysConfig *SysConfig
)

// 获取MC系统配置
func GetSysConfigFromManageCenterServer() error {
	//定义参数
	requestParamMap := make(map[string]string, 0)
	requestParamMap["IsResultCompressed"] = "false"

	//构造url
	url := fmt.Sprintf("%s/%s", mManageCenterServerAPIUrl, SYSCONF_URL_SUFFIX)

	//请求url,请求头
	header := webUtil.GetFormHeader()
	transport := webUtil.NewTransport()
	transport.DisableKeepAlives = true
	transport = webUtil.GetTimeoutTransport(transport, 30)

	statusCode, returnBytes, err := webUtil.PostMapData(url, requestParamMap, header, transport)
	//statusCode, returnBytes, err := webUtil.PostMapData(url, requestParamMap, header, nil)
	if err != nil {
		logUtil.ErrorLog(fmt.Sprintf("获取MC系统配置出错，url:%s,错误信息为:%s", url, err))
		return err
	}
	if statusCode != 200 {
		logUtil.ErrorLog(fmt.Sprintf("获取MC系统配置出错，url:%s,错误码为:%d", url, statusCode))
		return err
	}
	// 解析返回值
	returnObj := new(ReturnObject)
	if err = json.Unmarshal(returnBytes, &returnObj); err != nil {
		logUtil.ErrorLog(fmt.Sprintf("获取MC系统配置出错，反序列化返回值出错，错误信息为：%s, str:%s", err, string(returnBytes)))
		return err
	}

	// 判断返回状态是否为成功
	if returnObj.Code != 0 {
		// 数据没有变化，所以没有获取到新的数据，不能算错误。
		if returnObj.Code == 47 || returnObj.Message == "DataNotChanged" {
			return nil
		} else {
			msg := fmt.Sprintf("获取MC系统配置出错，返回状态：%d，信息为：%s", returnObj.Code, returnObj.Message)
			logUtil.ErrorLog(msg)
			return errors.New(msg)
		}
	}

	// 解析Data
	var tmpSysConfig *SysConfig
	if data, ok := returnObj.Data.(string); !ok {
		msg := "获取MC系统配置出错，返回的数据不是string类型"
		logUtil.ErrorLog(msg)
		return errors.New(msg)
	} else {
		if err = json.Unmarshal([]byte(data), &tmpSysConfig); err != nil {
			logUtil.ErrorLog(fmt.Sprintf("获取MC系统配置出错出错，反序列化数据出错，错误信息为：%s", err))
			return err
		}
	}

	// 赋值给最终的sysconfig
	mSysConfig = tmpSysConfig

	return nil
}

// 定时刷新MC系统配置
func StartRefreshSysConfigTread() {
	// 定时刷新数据
	go func() {
		goroutineName := "gameServerMgr.StartRefreshSysConfigTread"
		goroutineMgr.Monitor(goroutineName)
		defer goroutineMgr.ReleaseMonitor(goroutineName)

		for {
			// 每30秒刷新一次
			time.Sleep(30 * time.Second)

			// MC系统配置
			GetSysConfigFromManageCenterServer()
		}
	}()
}

// 获取系统配置
func GetSysConfig() *SysConfig {
	return mSysConfig
}
