<?php
namespace Gm\Model;
use Framework\Lib\Utils;
use Framework\Protobuf\InternalPacket;
use Gm\Config\Config;
use Gm\Config\ErrorCode;
use Gm\Core\RedisLib;
use Gm\Config\RedisConfig;
use Framework\Log\LogMark;

class Gms {
    // 存储请求数据
    public static function SaveMsgDB(int $serverID, int $msgID, string $token, $msg):bool {
        $ID = Servers::GetServerById($serverID)['server_id'];
        $rdb = RedisLib::GetInstance($ID);
        $key = "{" . $ID . "}" . RedisConfig::segmentation2 . RedisConfig::saveGameKey;
        $data = base64_encode($msg->serializeToString());
        $sendMsg = new InternalPacket();
        $sendMsg->setPacketId($msgID);
        $sendMsg->setPlayerId(0);
        $sendMsg->setSendServer($token);
        $sendMsg->setPacketData($data);
        $sendMsg->setSendTime(Utils::getServerTimestamp());
        LogMark::getInstance()->markInfo(
            'client save msg to db !',
            [
                'gm serverID' => $serverID,
                'serverID' => $ID,
                'msgID'    => $msgID,
                'token'    => $token,
                'msg'      => base64_encode($sendMsg->serializeToString()),
                'time'     => Utils::getServerTimestamp(),
            ]
        );
        if(!$rdb->rPush($key, base64_encode($sendMsg->serializeToString()))) {
            return false;
        }
        return true;
    }

    // 取请求数据
    public static function SearchMsgDB(string $token, int $msgID, &$data,int &$code, int $serverID,
                                       $s = Config::REQUEST_TIME_OUT): bool {
        $ID = Servers::GetServerById($serverID)['server_id'];
        $rdb = RedisLib::GetInstance($ID);
        $key = "{" . $token . "}" . RedisConfig::segmentation2 . RedisConfig::saveGameKey;
        $msg = $rdb->bLPop($key, $s);
        if(empty($msg)) {
            return false;
        }
        $resMsg = base64_decode($msg[1]);
        $message = new InternalPacket();
        $message->mergeFromString($resMsg);
        if($message->getPacketId() != $msgID) {
            return self::SearchMsgDB($token, $msgID, $data, $code, $serverID);
        }
        if($code != 0) {
            return false;
        }

        $data = $message->getPacketData();
        // 删除缓存
        $rdb->del($key);
        return true;
    }

    // 取请求数据
    public static function SearchServiceData(string $gmID, &$data): bool {
        $rdb = RedisLib::GetInstance();
        $key = "{" . $gmID . "}" . RedisConfig::segmentation2 . RedisConfig::searchGmKey;
        $msg = $rdb->bLPop($key, Config::SERVICE_TIME_OUT);
        if(empty($msg)) {
            return false;
        }
        $data = $msg;
        return true;
    }
}