<?php

/**
 * 房间内,玩家换服装
 */

namespace Game\Controller\Room;

use Framework\Define\ErrorDefine;
use Framework\MVC\ControllerBase;
use Framework\Network\SendMessage;
use Game\Constant\ClientErrorCode;
use Game\Logic\AccountLogic;
use Game\Logic\ItemLogic;
use Game\Logic\Room\RoomInfoLogic;
use Game\Protobuf\CGUpdateRoomPlayerCloth;
use Game\Protobuf\ClothData;
use Game\Protobuf\GCUpdateRoomPlayerCloth;
use Game\Protobuf\PacketId;

class CG_UpdateRoomPlayerCloth extends ControllerBase
{
    use RoomInfoLogic;
    use AccountLogic;
    use ItemLogic;

    private GCUpdateRoomPlayerCloth $sendMessage;

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

    public function run(): int
    {
        //检查服装
        $sex = $this->message->getGender();
        /**
         * @var ClothData $cloth
         */
        $cloth = $this->message->getCloth();
        if(!empty($cloth->getHairId())) {
            $clothArr[] = $cloth->getHairId();
        }
        if(!empty($cloth->getFaceId())) {
            $clothArr[] = $cloth->getFaceId();
        }
        if(!empty($cloth->getUpClothId())) {
            $clothArr[] = $cloth->getUpClothId();
        }
        if(!empty($cloth->getDownClothId())) {
            $clothArr[] = $cloth->getDownClothId();
        }
        if(!empty($cloth->getShoesId())) {
            $clothArr[] = $cloth->getShoesId();
        }
        $code = $this->checkClothIsInvalid($clothArr);
        if ($code == ClientErrorCode::CLIENT_SUCCESS) {
            $code = $this->updateRoomPlayerCloth(
                $this->message->getRoomID(),
                $this->message->getGender(),
                $cloth
            );
            if ($code == ClientErrorCode::CLIENT_SUCCESS) {
                $this->saveDress($sex, json_encode($clothArr));
                $this->sendMessage->setPlayerID($this->playerId);
                $this->sendMessage->setGender($sex);
                $this->sendMessage->setCloth($cloth);
            } else {
                $this->sendMessage->setCode($code);
            }
        } else {
            $this->sendMessage->setCode($code);
        }
        SendMessage::getInstance()->sendClient(PacketId::GC_UpdateRoomPlayerCloth, $this->sendMessage);
        return ErrorDefine::SUCCESS;
    }
}
