<?php
namespace slapper;

use pocketmine\scheduler\PluginTask;
use pocketmine\level\particle\BubbleParticle;
use pocketmine\math\Vector3;
use pocketmine\network\protocol\SetEntityDataPacket;
use slapper\entities\SlapperHuman;

class SlapperParticleTask extends PluginTask {
    private $tick = 0;

    public function onRun($currentTick) {
        $this->tick++;
        $radius = 1.0;
        $speed = 0.2;
        $angle = $this->tick * $speed;

        foreach ($this->getOwner()->getServer()->getLevels() as $level) {
            foreach ($level->getEntities() as $entity) {
                if ($entity instanceof SlapperHuman) {
                    // Particle logic
                    $x = $entity->x + $radius * cos($angle);
                    $z = $entity->z + $radius * sin($angle);
                    $y = $entity->y + 1.0 + sin($angle * 0.5) * 0.5;
                    $level->addParticle(new BubbleParticle(new Vector3($x, $y, $z)));

                    $x2 = $entity->x + $radius * cos($angle + M_PI);
                    $z2 = $entity->z + $radius * sin($angle + M_PI);
                    $y2 = $entity->y + 1.0 + cos($angle * 0.5) * 0.5;
                    $level->addParticle(new BubbleParticle(new Vector3($x2, $y2, $z2)));

                    // Sneak/Unsneak animation every 8 ticks
                    if ($this->tick % 8 === 0) {
                        $isSneaking = ($this->tick % 16 === 0);
                        $pk = new SetEntityDataPacket();
                        $pk->eid = $entity->getId();
                        $pk->metadata = [0 => [0, $isSneaking ? 2 : 0]];
                        foreach ($entity->getViewers() as $viewer) {
                            $viewer->dataPacket($pk);
                        }
                    }
                }
            }
        }
    }
}
