<?php

/**
 * UseItem.php
 * 使用道具
 * Created On 2021/01/20
 */

namespace Game\Controller\GameBag;

use Framework\Define\ErrorDefine;
use Framework\MVC\ControllerBase;
use Framework\Network\SendMessage;
use Game\Protobuf\GCUseItem;
use Game\Protobuf\ItemSingle;
use Game\Protobuf\PacketId;
use Game\Protobuf\UseItemSend;
use Game\Logic\ItemLogic;

class UseItem extends ControllerBase
{
    use ItemLogic;

    private GCUseItem $sendMessage;

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

    public function run(): int
    {
        $itemList = array();
        /**
         * @var ItemSingle $item
         */
        foreach ($this->message->getItem() as $item) {
            $uId = $item->getUid();
            $itemNum = $item->getNum();
            isset($itemList[$uId]) ? $itemList[$uId] += $itemNum : $itemList[$uId] = $itemNum;
        }
        $this->sendMessage->setCode($this->useItemByUIDArr($itemList));
        SendMessage::getInstance()->sendClient(PacketId::GC_UseItem, $this->sendMessage);
        return ErrorDefine::SUCCESS;
    }
}