<?php

namespace Robert\Sumo\Events;

use pocketmine\entity\Effect;
use pocketmine\event\Listener;
use pocketmine\event\entity\EntityDamageEvent;
use pocketmine\event\player\PlayerQuitEvent;
use pocketmine\event\player\PlayerInteractEvent;
use pocketmine\event\player\PlayerMoveEvent;
use pocketmine\Player;
use pocketmine\math\Vector3;
use Robert\Sumo\Main;

class EventListener implements Listener {
    private $base;

    public function __construct(Main $base)
    {
        $this->base = $base;
    }

    public function onDamage(EntityDamageEvent $e) {
        $en = $e->getEntity();
        if(!$en instanceof Player) return;
        $name = $en->getName();
        if(!$this->base->getHornyArenaManager()->isInGame($en->getName())) return;

        if($e instanceof \pocketmine\event\entity\EntityDamageByEntityEvent) {
            $e->setKnockBack(0.4);
            $p = $e->getEntity();
            //$p->getLevel()->addParticle(new \pocketmine\level\particle\CriticalParticle(new Vector3($p->getX(), $p->getY(), $p->getZ()), 5));
            //$p->getLevel()->addSound(new \pocketmine\level\sound\BlazeShootSound($p));


        }

        if($e->getCause() == EntityDamageEvent::CAUSE_VOID) {
            $arena = $this->base->getHornyArenaManager()->getArenaByPlayer($name);
            if($arena !== null) {
                $arena->broadcastMessage("§8(§eSumo§8) §e{$name}§f fell into the void!");
                $this->base->getHornyArenaManager()->leaveGame($name);
            }
        }
        
    }

    public function onQuit(PlayerQuitEvent $e) {
        $p = $e->getPlayer();
        $name = $p->getName();
        if($this->base->getHornyArenaManager()->isInGame($name)) {
            $p->removeAllEffects();
            $arena = $this->base->getHornyArenaManager()->getArenaByPlayer($name);
            if($arena !== null) {
                $this->base->getHornyArenaManager()->leaveGame($name);
            }
        }
    }

    public function onMove(PlayerMoveEvent $e) {
        $p = $e->getPlayer();
        if($this->base->getHornyArenaManager()->isInGame($p->getName())) {
            $arena = $this->base->getHornyArenaManager()->getArenaByPlayer($p->getName());
            if($arena !== null && !$arena->hasStarted()) {
                $e->setCancelled();
            }
        }
    }

    public function onInteract(PlayerInteractEvent $e) {
        $p = $e->getPlayer();
        $item = $e->getItem();
        if($item->getId() === 355 && $item->getCustomName() === "§r§cLeave Game") {
             if($this->base->getHornyArenaManager()->isInGame($p->getName())) {
                 $this->base->getHornyArenaManager()->leaveGame($p->getName());
             }
        }
    }
}
