<?php

namespace bedwars\entity;

use pocketmine\level\format\FullChunk;
use pocketmine\nbt\tag\CompoundTag;

use pocketmine\network\Network;
use pocketmine\network\protocol\AddItemEntityPacket;

use pocketmine\Player;

use pocketmine\entity\Projectile;
use pocketmine\entity\Entity;

use pocketmine\level\particle\RedstoneParticle;
use pocketmine\level\sound\EndermanTeleportSound;

use pocketmine\event\entity\ProjectileHitEvent;
use pocketmine\event\entity\EntityCombustByEntityEvent;
use pocketmine\event\entity\EntityDamageByChildEntityEvent;
use pocketmine\event\entity\EntityDamageByEntityEvent;
use pocketmine\event\entity\EntityDamageEvent;

use pocketmine\level\MovingObjectPosition;

use pocketmine\entity\Arrow;
use pocketmine\math\Vector3;

use pocketmine\item\Item;

use bedwars\BedWars;

use rocket\Rocket;
use rocket\entity\RocketBase;

class EnderPearl extends Projectile {
	
	const NETWORK_ID = 351;

	public $width = 0.25;
	public $length = 0.25;
	public $height = 0.25;

	protected $gravity = 0.03;
	protected $drag = 0.01;
	
	/**
	 * @param FullChunk   $chunk
	 * @param CompoundTag $nbt
	 * @param Entity      $shootingEntity
	 */
	public function __construct(FullChunk $chunk, CompoundTag $nbt, Entity $shootingEntity = null){
		parent::__construct($chunk, $nbt, $shootingEntity);
	}

	/**
	* @return string
	*/
	public function getName() {
		return "Ender Pearl";
	}
	
	/**
	 * @param float $currentTick
	 * @param return bool
     */
	public function onUpdate($currentTick){
		if($this->closed) {
			return false;
		}

		$tickDiff = $currentTick - $this->lastUpdate;
		
		if ($tickDiff <= 0 and !$this->justCreated) {
			return true;
		}
		
		$this->lastUpdate = $currentTick;
		$hasUpdate = $this->entityBaseTick($tickDiff);

		if($this->isAlive()){
			$movingObjectPosition = null;

			if (!$this->isCollided) {
				$this->motionY -= $this->gravity;
			}

			$moveVector = new Vector3($this->x + $this->motionX, $this->y + $this->motionY, $this->z + $this->motionZ);

			$list = $this->getLevel()->getCollidingEntities($this->boundingBox->addCoord($this->motionX, $this->motionY, $this->motionZ)->expand(1, 1, 1), $this);

			$nearDistance = PHP_INT_MAX;
			$nearEntity = null;

			foreach ($list as $entity) {
				if ($entity instanceof RocketBase or $entity == $this->shootingEntity) {
					continue;
				}

				$axisalignedbb = $entity->boundingBox->grow(0.3, 0.3, 0.3);
				$ob = $axisalignedbb->calculateIntercept($this, $moveVector);

				if ($ob === null) {
					continue;
				}

				$distance = $this->distanceSquared($ob->hitVector);

				if ($distance < $nearDistance) {
					$nearDistance = $distance;
					$nearEntity = $entity;
				}
			}

			if ($nearEntity !== null) {
				$movingObjectPosition = MovingObjectPosition::fromEntity($nearEntity);
			}

			if ($movingObjectPosition !== null) {
				if ($movingObjectPosition->entityHit !== null) {
					$this->server->getPluginManager()->callEvent(new ProjectileHitEvent($this));

					$motion = sqrt($this->motionX ** 2 + $this->motionY ** 2 + $this->motionZ ** 2);
					$damage = ceil($motion * $this->damage);

					if ($this->shootingEntity === null) {
						$ev = new EntityDamageByEntityEvent($this, $movingObjectPosition->entityHit, EntityDamageEvent::CAUSE_PROJECTILE, $damage);
					} else {
						$ev = new EntityDamageByChildEntityEvent($this->shootingEntity, $this, $movingObjectPosition->entityHit, EntityDamageEvent::CAUSE_PROJECTILE, $damage);
					}

					if ($movingObjectPosition->entityHit->attack($ev->getFinalDamage(), $ev) === true) {
						$ev->useArmors();
					}

					$this->hadCollision = true;

					if ($this->fireTicks > 0) {
						$ev = new EntityCombustByEntityEvent($this, $movingObjectPosition->entityHit, 5);
						$this->server->getPluginManager()->callEvent($ev);
						
						if(!$ev->isCancelled()){
							$movingObjectPosition->entityHit->setOnFire($ev->getDuration());
						}
					}

					$this->kill();
					return true;
				}
			}

			$this->move($this->motionX, $this->motionY, $this->motionZ);

			if ($this->isCollided and !$this->hadCollision) {
				$this->hadCollision = true;

				$this->motionX = 0;
				$this->motionY = 0;
				$this->motionZ = 0;

				$this->server->getPluginManager()->callEvent(new ProjectileHitEvent($this));
			} elseif(!$this->isCollided and $this->hadCollision) {
				$this->hadCollision = false;
			}

			if (!$this->onGround or abs($this->motionX) > 0.00001 or abs($this->motionY) > 0.00001 or abs($this->motionZ) > 0.00001) {
				$f = sqrt(($this->motionX ** 2) + ($this->motionZ ** 2));
				$this->yaw = (atan2($this->motionX, $this->motionZ) * 180 / M_PI);
				$this->pitch = (atan2($this->motionY, $f) * 180 / M_PI);
				$hasUpdate = true;
			}

			$this->updateMovement();
		}

		$this->level->addParticle(new RedstoneParticle($this));

		if ($this->isCollided or $this->hadCollision) {
			$this->kill();

			if ($this->isCollided or $this->hadCollision) {
				if ($this->shootingEntity instanceof Player) {
					$rocket = BedWars::$rocket;

					if ($rocket instanceof Rocket) {
						$rocket->leave($this->shootingEntity);
					}
					
					$this->shootingEntity->teleport($this);
					$this->level->addSound(new EndermanTeleportSound($this));
				}
			}
		}

		return $hasUpdate;
	}
	
	/**
	 * @param Player $player
	 */
	public function spawnTo(Player $player) {
		$pk = new AddItemEntityPacket();
		$pk->eid = $this->getId();
		$pk->x = $this->x;
		$pk->y = $this->y;
		$pk->z = $this->z;
		$pk->speedX = $this->motionX;
		$pk->speedY = $this->motionY;
		$pk->speedZ = $this->motionZ;
		$pk->item = Item::get(EnderPearl::NETWORK_ID, 5);
		$player->dataPacket($pk);

		parent::spawnTo($player);
	}
}