<?php

/**
 * 踢出玩家
 */

namespace Game\Controller\Gm;

use Framework\Define\ErrorDefine;
use Framework\Lib\Utils;
use Framework\MVC\ControllerBase;
use Framework\MVC\ModelManager;
use Framework\Network\SendServiceMsg;
use Game\Constant\ClientErrorCode;
use Game\Protobuf\GCSyncOutPlayer;
use Game\Protobuf\GMOutPlayer;
use Game\Protobuf\MGOutPlayer;
use Game\Protobuf\PacketId;
use Gm\Config\ErrorCode;
use Game\Logic\CommonConstLogic;
use Framework\Logic\OnLineLogic;
use Framework\Logic\PacketCacheLogic;
use Game\Logic\AccountLogic;
class OutPlayer extends ControllerBase
{
    use CommonConstLogic;
    use OnLineLogic;
    use PacketCacheLogic;
    use AccountLogic;

    private GMOutPlayer $sendMessage;
    private GCSyncOutPlayer $sendMsg;

    public function __construct()
    {
        $this->message = new MGOutPlayer();
        $this->sendMessage = new GMOutPlayer();
        $this->sendMsg = new GCSyncOutPlayer();
    }

    public function run(): int
    {
        $roleID = $this->message->getRoleID();
        $nickName = $this->message->getNickName();
        if(!empty($roleID)) {
            // 查询id
            $playerID = $this->searchPlayerIdByRoleID($roleID);

            if(empty($playerID)) {
                $this->sendMessage->setCode(ErrorCode::ERROR_ACCOUNT_NOT_FOUND);
                SendServiceMsg::getInstance()->sendServiceMsg(PacketId::GM_OutPlayer, $this->sendServer,
                    $this->sendMessage, 0, Utils::getServerTimestamp());
                return ErrorDefine::SUCCESS;
            }
        } else {
            $playerID = $this->searchPlayerIdByNickName($nickName);
            if(empty($playerID)) {
                $this->sendMessage->setCode(ErrorCode::ERROR_ACCOUNT_NOT_FOUND);
                SendServiceMsg::getInstance()->sendServiceMsg(PacketId::GM_OutPlayer, $this->sendServer,
                    $this->sendMessage, 0, Utils::getServerTimestamp());
                return ErrorDefine::SUCCESS;
            }
        }

        return $this->sendSuccessMessage(ErrorCode::SUCCESS, $playerID);
    }

    private function sendSuccessMessage(int $code, int $playerID): int
    {
        $this->sendMessage->setCode($code);
        SendServiceMsg::getInstance()->sendServiceMsg(
            PacketId::GM_OutPlayer,
            $this->sendServer,
            $this->sendMessage,
            0,
            Utils::getServerTimestamp()
        );

        ModelManager::getInstance()->setPlayerId($playerID);
        $this->playerId = $playerID;
        $this->addPacket(PacketId::GC_SyncOutPlayer, $this->sendMsg, $playerID);

        // clear session
        $this->saveLoginSessoin($this->playerId, "");

        return ErrorDefine::SUCCESS;
    }
}
