<?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\ModelTypeDefine;
use Game\Logic\AccountLogic;
use Game\Logic\Friend\FriendLogic;
use Game\Model\Friend\FriendModel;
use Game\Protobuf\GMUpdateFrinedIntimacy;
use Game\Protobuf\MGUpdateFrinedIntimacy;
use Game\Protobuf\PacketId;
use Gm\Config\ErrorCode;

class UpdateFriendIntimacy extends ControllerBase
{
    use FriendLogic;
    use AccountLogic;

    private GMUpdateFrinedIntimacy $sendMessage;

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

    public function run(): int
    {
        $account = $this->message->getAccount();
        //检查校验
        if(empty($account)) {
            return $this->sendMessage(ErrorCode::ERROR_ACCOUNT_NOT_FOUND);
        }
        $playerId = $this->searchPlayerIdByNickName($account);
        if ($playerId == 0) {
            return $this->sendMessage(ErrorCode::ERROR_ACCOUNT_NOT_FOUND);
        }
        //检查对方
        $targetAccount = $this->message->getTargetAccount();
        if(empty($targetAccount)) {
            return $this->sendMessage(ErrorCode::ERROR_ACCOUNT_NOT_FOUND);
        }
        $targetPlayerId = $this->searchPlayerIdByNickName($targetAccount);
        if ($targetPlayerId == 0) {
            return $this->sendMessage(ErrorCode::ERROR_ACCOUNT_NOT_FOUND);
        }
        ModelManager::getInstance()->clearModelList();
        ModelManager::getInstance()->setPlayerId($playerId);
        //检查是否为好友
        if (!$this->checkTargetPlayerIsMyFriend($targetPlayerId)) {
            return $this->sendMessage(ErrorCode::ERROR_TARGET_NOT_FRIEND);
        }
        /**
         * @var FriendModel $friend
         */
        $friend = ModelManager::getInstance()->getModel(ModelTypeDefine::FRIEND);
        $friend->setRespondentPlayerId($targetPlayerId);
        //检查扣除亲密度
        $addPoint = $this->message->getScore();
        if ($addPoint < 0) {
            $friendData = $friend->getFriendData();
            if ($friendData->intimacy + $addPoint < 0) {
                return $this->sendMessage(ErrorCode::ERROR_SUB_FRIEND_INTIMACY_LESS_ZERO);
            }
        }
        $friend->addIntimacy($addPoint, true);
        return $this->sendMessage(ErrorCode::SUCCESS);
    }

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