<?php

/**
 * 控制器基类
 * Created On 2021/11/1
 * @author yuanb yuanbo0x@gmail.com
 */

namespace Framework\MVC;

use Exception;
use Framework\Define\ErrorDefine;
use Framework\Log\LogMark;
use Game\Protobuf\PacketId;
use Google\Protobuf\Internal\Message;

/**
 * 控制器基类
 */


class ControllerBase
{
    /**
     * @var Message $message 网络消息基类
     */
    protected Message $message;

    protected int $playerId;
    protected string $sendServer;

    public function init($playerId)
    {
        $this->playerId = $playerId;
    }

    public function setSendServer(string $sendServer) {
        $this->sendServer = $sendServer;
    }

    /**
     * 解析网络字符串转成网络消息包
     * @param string $data 网络消息字符串
     * @param int $packet_id 消息id
     * @return int 解析的结果
     */
    public function parsing(string $data, int $packet_id): int
    {
        try {
            $this->message->mergeFromString($data);
        } catch (Exception $e) {
            LogMark::getInstance()->markError(
                ErrorDefine::REQUEST_PARAM_ERROR,
                "catch exception:parsing proto byte error",
                array("exception" => $e->getMessage(), "data" => $data)
            );
            return ErrorDefine::REQUEST_PARAM_ERROR;
        }
        //日志忽略消息列表
        $ignorePacketList = array(
            PacketId::CG_HeartBeat,     //普通心跳
        );
        if (!in_array($packet_id, $ignorePacketList)) {
            LogMark::getInstance()->markDebug(
                "finish parsing packet",
                array(
                    "packetId" => $packet_id,
                    "packet" => $this->message->serializeToJsonString()
                )
            );
        }
        return ErrorDefine::SUCCESS;
    }

    /**
     * 需要子类继承去实现
     * 控制执行逻辑
     * @return int 执行结果
     */
    public function run(): int
    {
        return ErrorDefine::SUCCESS;
    }
}
