<?php

namespace bedwars\entity;

use pocketmine\Player;

use bedwars\entity\api\EntityAPI;

use pocketmine\item\Item;

use pocketmine\network\protocol\AddEntityPacket;
use pocketmine\network\protocol\AddPlayerPacket;
use pocketmine\network\protocol\RemoveEntityPacket;
use pocketmine\utils\UUID;

use pocketmine\event\entity\EntityDamageEvent;
use pocketmine\event\entity\EntityDamageByEntityEvent;

use pocketmine\level\Position;

use pocketmine\nbt\tag\CompoundTag;
use pocketmine\nbt\tag\StringTag;
use pocketmine\nbt\tag\ListTag;
use pocketmine\nbt\tag\DoubleTag;
use pocketmine\nbt\tag\ShortTag;
use pocketmine\nbt\tag\FloatTag;
use pocketmine\nbt\tag\ByteTag;
use pocketmine\nbt\tag\IntTag;

use pocketmine\entity\Entity;

use bedwars\BedWars;

class VillagerNPC extends EntityAPI {

    /** 
    * @param int               $damage
    * @param EntityDamageEvent $source
    */    
    public function attack($damager, EntityDamageEvent $source) {
        if ($source instanceof EntityDamageByEntityEvent) {
            $damager = $source->getDamager();
            
            if ($damager instanceof Player) {
                if ($this->open($damager)) {
                    
                } elseif ($damager->getInventory()->getItemInHand()->getId() == 388 and $damager->isOp()) {
                    $this->close();
                }
            }
        }
    }

    /**
    * @param string   $name 
    * @param Position $position
    * @param float    $yaw
    * @param float   $pitch
    */
    public static function createNBT(Position $position, $yaw , $pitch) : CompoundTag {
        $nbt = new CompoundTag("", []);
        $nbt->Pos = new ListTag("Pos", [
            new DoubleTag(0, $position->x),
            new DoubleTag(1, $position->y),
            new DoubleTag(2, $position->z)
        ]);
        $nbt->Rotation = new ListTag("Rotation", [
            new DoubleTag(0, $yaw),
            new DoubleTag(1, $pitch)
        ]);
        $nbt->Motion = new ListTag("Motion", [
            new DoubleTag(0, 0),
            new DoubleTag(1, 0),
            new DoubleTag(2, 0)
        ]);
        
        $nbt->Health = new ShortTag("Health", 1);
        $nbt->Parent = new CompoundTag("Parent", []);
        $nbt->Viewers = new CompoundTag("Viewers", []);
        return $nbt;
    }
    
    /**
    * @param Player $player
    */
    public function spawnTo(Player $player) {
        $pk = new AddEntityPacket();
        $pk->eid = $this->getId();
        $pk->type = $this->type;
        $pk->x = $this->x;
        $pk->y = $this->y;
        $pk->z = $this->z;
        $pk->yaw = $this->yaw;
        $pk->pitch = $this->pitch;
        $pk->metadata = [
            15 => [0, 1],
            23 => [7, -1],
            24 => [0, 0]
        ];
        $player->dataPacket($pk);

        $this->addLines($this->nametag);
        
        parent::spawnTo($player);
    }
}