<?php

/**
 * 新手引导保存步骤
 */

namespace Game\Controller\Account;
use Framework\Define\ErrorDefine;
use Framework\Log\LogMark;
use Framework\MVC\ControllerBase;
use Framework\Network\SendMessage;
use Game\Constant\ClientErrorCode;
use Game\Constant\ConstTemplate\TemplateConst;
use Game\Constant\GameErrorCode;
use Game\Constant\TemplateDefine;
use Game\Data\AccountData;
use Game\Logic\AccountLogic;
use Game\Protobuf\CGSaveGuideStep;
use Game\Protobuf\GCSaveGuideStep;
use Game\Protobuf\PacketId;

class SaveGuideStep extends ControllerBase
{
    use AccountLogic;
    private GCSaveGuideStep $sendMsg;
    public function __construct()
    {
        $this->message = new CGSaveGuideStep();
        $this->sendMsg = new GCSaveGuideStep();
    }

    public function run(): int
    {
        $step = $this->message->getStep();

        // 如果请求次数过多则拒绝请求
        $maxNum = $this->getTerm(TemplateDefine::TYPE_CONST,
            TemplateConst::Const_Save_Step_Limit,
            TemplateConst::ConstNum);
        if($step > $maxNum) {
            $this->sendMsg(ClientErrorCode::LOGIN_STEP_NUM_ERROR, $step);
            return ErrorDefine::SUCCESS;
        }

        $data = [
            AccountData::DB_STEP => $step,
        ];

        if (!$this->saveAccountData($data)) {
            LogMark::getInstance()->markError(
                GameErrorCode::UPDATE_ROLE_ERROR,
                '[control] update guide step account data error!');
            $this->sendMsg(ClientErrorCode::SAVE_GUIDE_STEP_ERROR, $step);
            return ErrorDefine::SUCCESS;
        }
        $this->sendMsg(ClientErrorCode::CLIENT_SUCCESS, $step);
        return ErrorDefine::SUCCESS;
    }

    private function sendMsg(int $code, int $step)
    {
        $this->sendMsg->setCode($code);
        $this->sendMsg->setStep($step);
        SendMessage::getInstance()->sendClient(PacketId::GC_SaveGuideStep, $this->sendMsg);
    }
}