package gameServerMgr

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"strconv"

	. "Framework/managecenterModel"
	"goutil/webUtil"
	"goutil/zlibUtil"
)

// 区服激活地址后缀
const ActivateServer_URL_SUFFIX string = "/API/ServerActivate.ashx"

var (
	mManageCenterServerAPIUrl string
	mIsInit                   bool = true
)

// 解析从ManagecenterServer中获取的服务器相关数据
func ParseInfoFromManageCenterServer(serverGroupId int32, data string) {
	var deserializedData map[string]interface{}
	err := json.Unmarshal([]byte(data), &deserializedData)
	if err != nil {
		return
	}

	//解析服务器组
	var serverGroup *ServerGroup
	err = json.Unmarshal([]byte(deserializedData["ServerGroupInfo"].(string)), &serverGroup)
	if err != nil {
		return
	}

	//解析合作商
	var partnerList []*Partner
	err = json.Unmarshal([]byte(deserializedData["PartnerList"].(string)), &partnerList)
	if err != nil {
		return
	}

	//解析服务器列表
	var serverList []*Server
	err = json.Unmarshal([]byte(deserializedData["ServerList"].(string)), &serverList)
	if err != nil {
		return
	}

	//解析资源包
	var resourceList []*ResourceVersion
	err = json.Unmarshal([]byte(deserializedData["ResourceVersionList"].(string)), &resourceList)
	if err != nil {
		return
	}

	//解析大区
	var areaList []*Area
	err = json.Unmarshal([]byte(deserializedData["AreaList"].(string)), &areaList)
	if err != nil {
		return
	}

	//判断是否需要更新数据（如果ServerGroupId不匹配，则不解析数据）
	if serverGroupId != serverGroup.Id {
		return
	}

	//缓存服务器组
	ParseServerGroupInfo(serverGroup)

	//缓存合作商
	ParsePartnerInfo(partnerList)

	//缓存合作商对应的充值配置
	ParseChargeConfigInfo(partnerList)

	//缓存服务器
	ParseServerInfo(serverList)

	//缓存资源包
	ParseResourceVersionInfo(resourceList)

	//缓存大区
	ParseAreaInfo(areaList)
}

// 激活服务器
func ActiveServer(manageCenterServerAPIUrl string, serverGroupId int32) error {
	if len(manageCenterServerAPIUrl) == 0 {
		return fmt.Errorf("ManageCenterServerAPI地址不能为空")
	}
	mManageCenterServerAPIUrl = manageCenterServerAPIUrl

	//定义参数
	requestParamMap := make(map[string]string, 0)
	requestParamMap["ServerGroupID"] = strconv.Itoa(int(serverGroupId))

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

	//请求url,请求头
	header := webUtil.GetFormHeader()
	transport := webUtil.NewTransport()
	transport.DisableKeepAlives = true
	transport.TLSClientConfig = &tls.Config{
		InsecureSkipVerify: 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 {
		return err
	}
	if statusCode != 200 {
		return fmt.Errorf("StatusCode:%d", statusCode)
	}

	//解压缩
	retBytes, err1 := zlibUtil.Decompress(returnBytes)
	if err1 != nil {
		return err1
	}
	// 解析返回值
	returnObj := new(ReturnObject)
	if err = json.Unmarshal(retBytes, &returnObj); err != nil {
		return err
	}

	// 判断返回状态是否为成功
	if returnObj.Code != 0 {
		return fmt.Errorf("code:%d,Message:%s", returnObj.Code, returnObj.Message)
	}

	//解析得到的数据
	ParseInfoFromManageCenterServer(serverGroupId, returnObj.Data.(string))

	//获取白名单
	GetWhiteListFromManageCenterServer()

	//如果是初始化，则开启白名单刷新线程。避免游戏客户端刷新数据的时候重复开启线程
	if mIsInit {
		//启动白名单数据刷新线程
		StartRefreshWhiteListTread()

		//启动刷新MC系统配置
		StartRefreshSysConfigTread()
		//初始化修改为fasle
		mIsInit = false
	}

	return nil
}
