<?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\item\Item;
use pocketmine\block\Block;

use bedwars\util\Explosion;
use pocketmine\level\particle\RedstoneParticle;

class FireBall extends Projectile {
	
	const NETWORK_ID = 378;

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

	protected $gravity = 0.03;
	protected $drag = 0.01;

	protected $explodeTime;
	protected $damage;
	protected $blocks;

	protected $time;

	/**

	 * @param FullChunk   $chunk
	 * @param CompoundTag $nbt
	 * @param Entity      $shootingEntity
	 */
	public function __construct(FullChunk $chunk, CompoundTag $nbt, Entity $shootingEntity = null) {
		$this->blocks = [Block::WOOL];
		$this->damage = 4;
		parent::__construct($chunk, $nbt, $shootingEntity);
	}
	
	/**
	* @return string
	*/
	public function getName() {
		return "Fire Ball";
	}

	/**
	* @param int $time
	*/
	public function setExplodeTime(int $time = 80) {
		$this->explodeTime = $time;
	}

	/**
	* @param int $damage
	*/
	public function setDamage(int $damage) {
		$this->damage = $damage;
	}

	/**
	* @param array $blocks
	*/
	public function setBlocks(array $blocks) {
		$this->blocks = $blocks;
	}
	
	/**
	 * @param float $currentTick
	 * @param return bool
	 */
	public function onUpdate($currentTick) {
		if ($this->closed) {
			return false;
		}

		$this->timings->startTiming();
		$hasUpdate = parent::onUpdate($currentTick);

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

		$canExplode = false;

		if (is_int($this->explodeTime)) {
			$this->explodeTime--;

			if ($this->explodeTime <= 0) {
				$canExplode = true;
			}
		}

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

			if ($this->isCollided or $this->hadCollision or $canExplode) {
				$this->explode();
			}
			
			$hasUpdate = true;
		}

		$this->timings->stopTiming();

		return $hasUpdate;
	}

	public function explode() {
		$explosion = new Explosion($this, 2, $this, $this->blocks, $this->damage);
		$explosion->explodeA();
		$explosion->explodeB();
	}
	
	/**
	 * @param Player $playe
	 */
	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(FireBall::NETWORK_ID);
		$player->dataPacket($pk);

		parent::spawnTo($player);
	}
}