<?php
namespace slapper\entities;

use pocketmine\entity\Human;
use pocketmine\network\protocol\AddPlayerPacket;
use pocketmine\network\protocol\PlayerListPacket;
use pocketmine\Player;

class SlapperHuman extends Human {

    public function getDisplayName(Player $player) {
        $name = $this->getDataProperty(2);
        $main = \pocketmine\Server::getInstance()->getPluginManager()->getPlugin("Slapper");
        if ($main instanceof \slapper\Main) {
            $worldData = $main->getConfig()->get("world_placeholders", []);
            foreach (["world1", "world2", "world3", "world4"] as $key) {
                if (isset($worldData[$key])) {
                    $worldName = $worldData[$key];
                    $count = 0;
                    $level = \pocketmine\Server::getInstance()->getLevelByName($worldName);
                    if ($level !== null) {
                        $count = count($level->getPlayers());
                    }
                    $name = str_replace("{" . $key . "}", (string)$count, $name);
                }
            }
        }
        return str_ireplace(["{name}", "{display_name}"], [$player->getName(), $player->getDisplayName()], $player->hasPermission("slapper.seeId") ? $name . "\n" . \pocketmine\utils\TextFormat::GREEN . "Entity ID: " . $this->getId() : $name);
    }

    public function spawnTo(Player $player)
    {
        if ($player !== $this and !isset($this->hasSpawned[$player->getLoaderId()])) {
            $this->hasSpawned[$player->getLoaderId()] = $player;

            $uuid = $this->getUniqueId();
            $entityId = $this->getId();

            $pk = new AddPlayerPacket();
            $pk->uuid = $uuid;
            $pk->username = "";
            $pk->eid = $entityId;
            $pk->x = $this->x;
            $pk->y = $this->y;
            $pk->z = $this->z;
            $pk->yaw = $this->yaw;
            $pk->pitch = $this->pitch;
            $pk->item = $this->getInventory()->getItemInHand();
            $pk->metadata = [
                0 => [0, 2], // DATA_FLAGS => DATA_FLAG_SNEAKING
                2 => [4, $this->getDisplayName($player)],
                3 => [0, $this->getDataProperty(3)],
                15 => [0, 1],
                        23 => [7, -1],
                        24 => [0, 0]
            ];
            $player->dataPacket($pk);

            $this->inventory->sendArmorContents($player);

            $add = new PlayerListPacket();
            $add->type = 0;
            $add->entries[] = [$uuid, $entityId, isset($this->namedtag->MenuName) ? $this->namedtag["MenuName"] : "", $this->skinId, $this->skin];
            $player->dataPacket($add);
            if ($this->namedtag["MenuName"] === "") {
                $remove = new PlayerListPacket();
                $remove->type = 1;
                $remove->entries[] = [$uuid];
                $player->dataPacket($remove);
            }
        }
    }
}
