<?php

/**
 * CGHeartBeatHandler.php
 * 文件描述
 * Created On 2022/1/26
 * @author yuanb yuanbo0x@gmail.com
 */

namespace Game\Controller;

use Framework\Define\ErrorDefine;
use Framework\Lib\Utils;
use Framework\MVC\ControllerBase;
use Framework\Network\SendMessage;
use Framework\Logic\OnLineLogic;
use Framework\Logic\TimerLogic;
use Game\Constant\GameConstantDefine;
use Game\Data\AccountData;
use Game\Data\RoleExtData;
use Game\Logic\AccountLogic;
use Game\Logic\NoticeLogic;
use Game\Protobuf\CGHeartBeat;
use Game\Protobuf\GCUpdateTime;
use Game\Protobuf\PacketId;

class CGHeartBeatHandler extends ControllerBase
{
    use TimerLogic;
    use OnLineLogic;
    use NoticeLogic;
    use AccountLogic;

    private GCUpdateTime $sendMessage;

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

    public function run(): int
    {
        if ($this->playerId == 0) {
            return ErrorDefine::SUCCESS;
        }
        $time = Utils::getServerTimestamp();
        $this->sendMessage->setServerTime($time);
        //检查是否注册完成
        $param = [
            AccountData::DB_STEP,
            RoleExtData::DB_Status,
        ];
        $playerInfo = $this->getAccountPropertyArr($this->playerId, $param);
        if ($playerInfo[AccountData::DB_STEP] < GameConstantDefine::STEP_COMPLETE) {
            SendMessage::getInstance()->sendClient(PacketId::GC_UpdateTime, $this->sendMessage);
            return ErrorDefine::SUCCESS;
        }
        $this->timerHeartBeat($time);
        $this->updteOnineTime($time);
        $this->reLogin($playerInfo[RoleExtData::DB_Status]);
        SendMessage::getInstance()->sendClient(PacketId::GC_UpdateTime, $this->sendMessage);
        return ErrorDefine::SUCCESS;
    }

    //更新在线时间
    private function updteOnineTime(int $time)
    {
        $this->updateTimeById($this->playerId, $time);
    }

    //重新登录
    private function reLogin(int $status)
    {
        if ($status == GameConstantDefine::PLAYER_STATUS_OFFLINE) {
            $this->upRoleStatus(GameConstantDefine::PLAYER_STATUS_ONLINE, $this->playerId);
        }
    }
}
