<?php

/**
 * Service.php
 */

namespace Gm\CLI;

use Framework\Log\LogMark;
use Framework\Protobuf\InternalPacket;
use Gm\Config\Config;
use Gm\Config\ErrorCode;
use Gm\Model\Gms;
use Google\Protobuf\Internal\Message;

class Service
{
    public array $msgData = [];
    /**
     * @var Message $message
     */
    public Message $message;

    public function run(): int
    {
        $this->getRDBData();
        if(empty($this->msgData)) {
            return ErrorCode::SUCCESS;
        }

        $message = new InternalPacket();
        $message->mergeFromString(base64_decode($this->msgData[1]));
        $packetID = $message->getPacketId();
        $sendTime = $message->getSendTime();
        $playerID = $message->getPlayerId();
        $sendServer = $message->getSendServer();
        $data = $message->getPacketData();
        $controller_name = Config::SERVICE_CONTROLLER;
        $controller = new $controller_name();
        $func = Config::MODEL_SERVICE[$packetID];
//        $this->message->mergeFromString($data);

        if(ErrorCode::SUCCESS !== $controller->$func($data)) {
            LogMark::getInstance()->markInfo(
                '[gm service] controller run error!',
                [$packetID, $sendTime, $sendServer, $playerID]
            );
            return ErrorCode::ERROR_SERVICE_FAIL;
        }
        return ErrorCode::SUCCESS;
    }

    public function getRDBData():bool {
        if(!Gms::SearchServiceData(Config::GM_ID, $this->msgData)) {
            LogMark::getInstance()->markWarn(
                ErrorCode::ERROR_SERVICE_FAIL,
                '[gm service] exec data error!',
                ['gmID' => Config::GM_ID]
            );

            return false;
        }
        return true;
    }
}
