<?php

/**
 * 跑马灯编辑
 */

namespace Game\Controller\Gm;

use Framework\Define\ErrorDefine;
use Framework\Lib\Utils;
use Framework\Log\LogMark;
use Framework\MVC\ControllerBase;
use Framework\Network\SendServiceMsg;
use Game\Constant\DBTableDefine;
use Game\Constant\ModelTypeDefine;
use Game\Protobuf\GMLampAdd;
use Game\Protobuf\MGLampAdd;
use Game\Protobuf\PacketId;
use Gm\Config\ErrorCode;
use Framework\DB\Handler\CommonDBHandler;
use Framework\Logic\CommonDataLogic;

class LampAdd extends ControllerBase
{
    use CommonDBHandler;
    use CommonDataLogic;
    private GMLampAdd $sendMessage;

    public function __construct()
    {
        $this->message = new MGLampAdd();
        $this->sendMessage = new GMLampAdd();
    }

    public function run(): int
    {
        $id = $this->message->getID();
        // 如果id比最新发布的要小 则不发布
        $commonID = $this->getCommonValueByModel(ModelTypeDefine::LAMP);
        if(!is_null($commonID) && ($id <= $commonID)) {
            return ErrorDefine::SUCCESS;
        }

        // 更新全局跑马灯数据
        $this->addCommonData(ModelTypeDefine::LAMP, $id);

        // 新增数据
        $data[$id] = base64_encode($this->message->serializeToString());
        $this->updateCommonTitle(DBTableDefine::TABLE_LAMP, 0, $data);
        return $this->sendSuccessMessage(ErrorCode::SUCCESS);
    }

    private function sendSuccessMessage(int $code): int
    {
        $this->sendMessage->setCode($code);
        SendServiceMsg::getInstance()->sendServiceMsg(
            PacketId::GM_LampAdd,
            $this->sendServer,
            $this->sendMessage,
            0,
            Utils::getServerTimestamp()
        );
        return ErrorDefine::SUCCESS;
    }
}
