<?php

/**
 * 玩家增益buff
 */

namespace Game\Method\Player;

use Framework\Lib\Utils;
use Framework\Log\LogMark;
use Framework\MVC\ModelManager;
use Framework\Network\SendMessage;
use Game\Constant\ConstTemplate\TemplateItem;
use Game\Constant\GameErrorCode;
use Game\Constant\ModelTypeDefine;
use Game\Model\AccountModel;
use Game\Protobuf\GCUpdatePlayerBuff;
use Game\Protobuf\PacketId;

trait PlayerBuffLogic
{
    //增加buff
    public function addPlayerBuff(string $itemBuffName, int $addTime): bool
    {
        //检查字段
        if (array_key_exists($itemBuffName, TemplateItem::ITEM_BUFF_2_ACCOUNT_DATA)) {
            $accountBuffName = TemplateItem::ITEM_BUFF_2_ACCOUNT_DATA[$itemBuffName];
            /**
             * @var AccountModel $account
             */
            $account = ModelManager::getInstance()->getModel(ModelTypeDefine::ACCOUNT);
            $account->searchAccount($accountInfo);
            $buffTime = $accountInfo[$accountBuffName] ?? 0;
            $now = Utils::getServerTimestamp();
            if ($buffTime >= $now) {
                //延长时间
                $expireTime = $buffTime + $addTime;
            } else {
                $expireTime = $now + $addTime;
            }
            $data = array(
                $accountBuffName => $expireTime
            );
            $account->saveAccount($data);
            //通知时间更新
            $this->sendUpdateBuffMessage($account);
            return true;
        }
        LogMark::getInstance()->markError(
            GameErrorCode::CONFIG_ERROR,
            "[PlayerBuffLogic] not found Item buff name",
            array(
                "itemBuffName" => $itemBuffName
            )
        );
        return false;
    }

    //通知时间更新
    private function sendUpdateBuffMessage(AccountModel $account)
    {
        $message = new GCUpdatePlayerBuff();
        $account->searchAccount($accountInfo);
        foreach (TemplateItem::ITEM_BUFF_2_ACCOUNT_DATA as $t => $key) {
            $value = $accountInfo[$key] ?? 0;
            $proKey = "set{$key}";
            $message->$proKey($value);
        }
        SendMessage::getInstance()->sendClient(PacketId::GC_UpdatePlayerBuff, $message);
    }

    //检查buff是否生效
    public function checkBuffActivate(string $buffName): bool
    {
        /**
         * @var AccountModel $account
         */
        $account = ModelManager::getInstance()->getModel(ModelTypeDefine::ACCOUNT);
        $account->searchAccount($accountInfo);
        $buffTime = $accountInfo[$buffName] ?? 0;
        $now = Utils::getServerTimestamp();
        return $buffTime >= $now;
    }
}
