<?php

namespace bedwars\util;

use bedwars\game\BasicGame;
use bedwars\entity\BedText;

use pocketmine\math\Vector3;

use pocketmine\item\Item;

use pocketmine\level\Level;

use pocketmine\nbt\tag\CompoundTag;
use pocketmine\nbt\tag\DoubleTag;
use pocketmine\nbt\tag\ListTag;
use pocketmine\nbt\tag\StringTag;
use pocketmine\nbt\tag\IntTag;

class Bed {

	/** @var array */
    private $entities = array();
    
    /** @var BasicGame */
    private $basicGame;
    
    /**
     * @param BasicGame $game
     */
    public function __construct(BasicGame $basicGame) {
        $this->basicGame = $basicGame;
    }

    public function start() {
        foreach ($this->basicGame->teams as $name => $team) {
            $this->setText($name);
        }

        foreach ($this->basicGame->defaultTeams as $name => $args) {
            if (!isset($this->basicGame->teams[$name]) and isset($args["beds"])) {
                $bed = explode(":", $args["beds"]);

                $this->basicGame->level->loadChunk($bed[0], $bed[2], true);
                
                $block = $this->basicGame->level->getBlock(new Vector3($bed[0], $bed[1], $bed[2]));
                
                if ($block->getId() === 26) {
                    $block->onBreak(Item::get(0));
                }
            }
        }
    }
    
    public function close() {
        foreach ($this->entities as $id => $entity) {
            if ($entity instanceof BedText) {
                unset($this->entities[$id]);
            	$entity->close();
            }
        }
    }
    
    /**
     * @param string $team
     */
    public function setText(string $team) {
        if (!($this->basicGame->level instanceof Level)) {
        	return false;
        }
        
        $args = $this->basicGame->defaultTeams[$team];
        $bed = explode(":", $args['beds']);

        $chunk = $this->basicGame->level->getChunk($bed[0] >> 4, $bed[2] >> 4, true);
        
        $nbt = new CompoundTag("", []);
        
        $nbt->Pos = new ListTag("Pos", array(
            new DoubleTag(0, $bed[0] + 0.5),
            new DoubleTag(0, $bed[1] - 1.55),
            new DoubleTag(0, $bed[2] + 0.5),
        ));

        $nbt->Rotation = new ListTag("Rotation", array(
            new DoubleTag(0, 0),
            new DoubleTag(0, 0)
        ));

        $nbt->Motion = new ListTag("Motion", array(
            new DoubleTag(0, 0),
            new DoubleTag(0, 0),
            new DoubleTag(0, 0)
        ));

        $nbt->Team = new StringTag("Team", $team);
        $nbt->GameId = new StringTag("GameId", $this->basicGame->getName());
        $nbt->Alive = new IntTag("Alive", 1);
        
		$nbt->Invisible = new IntTag("Invisible", 1);
        
        $nbt->Parent = new CompoundTag("Parent", []);
		$nbt->Viewers = new CompoundTag("Viewers", []);
        
        $text = new BedText($chunk, $nbt);
        $text->spawnToAll();
        
        $this->entities[$text->getId()] = $text;
    }
}
?>