<?php

namespace bedwars\command;

use pocketmine\command\Command;
use pocketmine\command\CommandSender;

use pocketmine\Player;

use pocketmine\nbt\tag\StringTag;

use bedwars\BedWars;
use bedwars\util\Util;
use bedwars\game\Game;

use bedwars\entity\Shop;
use bedwars\entity\Upgrade;
use bedwars\entity\Manager;
use bedwars\entity\BedWarsWins;

class GameCommand extends Command {

    /** @var BedWars */    
    private $plugin;

    /**
     * GameCommand __construct
     * 
     * @param BedWars $plugin
    */
	public function __construct(BedWars $plugin) {
		parent::__construct(
			"bedwars", 
			"§agerenciar o plugin de bedwars",
			"§ause: /bedwars help",
			["bw"]
		);
		parent::setPermission("bedwars.command.permission");
        $this->plugin = $plugin;
	}

	/**
	* @param CommandSender $sender
	* @param string        $currentAliass
	* @param array         $arg
	*/
	public function execute(CommandSender $sender, $currentAlias, array $args) {
		if (!($sender instanceof Player)) {
			$sender->sendMessage($this->usageMessage);
			return false;
		}
		
		if (count($args) > 0) {
            switch (strtolower($args[0])) {
                case "criar":
                case "create":
                    if ($sender->hasPermission($this->getPermission()) === false) {
                        $sender->sendMessage($this->usageMessage);
                        break;
                    }
                    if (count($args) < 3) {
                        $sender->sendMessage("§cTente usar /bw criar <nome> <modo> <teams> ");
                        break;
                    }
                    
                    $name = (string) $args[1];
                    $mode = (string) strtolower($args[2]);
                    $list = (array) $args;
                    
                    array_shift($list);
                    array_shift($list);
                    array_shift($list);

                    if (strlen($name) >= 15 or !in_array($mode, array("solo", "duo", "squad")) or empty($list)) {
                        $sender->sendMessage("§cO nome deve ser menor que 15 e o modo deve ser solo, duo ou squad, e as equipes ex: Verde=a Vermelho=c Amarelo=e Azul=9");
                        break;
                    }
                    
                    $world = $sender->level;
                    
                    if (Util::is_buggy_map($world)) {
                    	$sender->sendMessage("§cO mapa na qual você está, possui um problema em seu level.dat acabamos de conserta! #");
                    }
                    
                    $teams = array();
                    foreach ($list as &$team) {
                        $explode = explode("=", $team);
                        
                        if (!isset($explode[1])) {
                            $sender->sendMessage("§cA equipe " . ucfirst(str_replace("=", "", $team)) . " està sem cor!");
                            continue;
                        }
                        $teams[$explode[0]] = array("color" => strtolower($explode[1]));
                        $team = "§" . strtolower($explode[1]) . ucfirst($explode[0]);
                    }
                    
                    $game = new Game();
                    $game->setName($name);
                    $game->setMode($mode);
                    $game->setWorld($world->getFolderName());
                    $game->setDefaultTeams($teams);
                    $game->setGeneretors(array());
                    $game->setHub(array());

                    $game->backupMap(true);
                    $game->reset();
                    
                    $this->plugin->arenas[$name] = $game;
                    
                    $sender->sendMessage("§aArena criada! cujo nome é " . $name . ", e as equipes são: " . implode(", ", $list));
                    break;
                
                case "set":
                    if ($sender->hasPermission($this->getPermission()) === false) {
                        $sender->sendMessage($this->usageMessage);
                        break;
                    }
                    $game = $this->plugin->getGame($sender, true);
                    
                    if ($game === false) {
                    	$sender->sendMessage("§aPor favor entre em uma arena!");
                    	break;
                    }

                    if (count($args) < 2) {
                        $sender->sendMessage("§a/bw set <hub|spawns|ores|beds|generetors>");
                        break;
                    }

                    switch (($type = strtolower($args[1]))) {
                        case "hub":
                            $world = $sender->level;
                            if (Util::is_buggy_map($world)) {
                                //TODO:
                            }
                            $game->setHub(array($sender->x + 0.5, $sender->y, $sender->z + 0.5, $world->getFolderName(), $sender->yaw));
                            $sender->sendMessage("§aO hub do jogo " . $game->getName() . " foi setado!");
                            break;
                        
                        case "spawns":
                        case "beds":
                        case "ores":
                        case "generetors":
                            $team = (string) key($game->defaultTeams);
                            $color = "§" . current($game->defaultTeams)["color"];
                            if ($type == "generetors") {
                                $team = "diamond"; //first generetor
                                $color = "§b";
                            }
                            
                            $this->plugin->event->setActive($sender, $type, $team);
                            $sender->sendMessage("§aBata na posicao para marca os " . $type . " iniciar com o " . $color . $team);
                            break;
                        
                        default:
                            $sender->sendMessage("§a/bw set <hub|spawns|ores|beds|generetors>");
                            break;
                    }
                    break;

                case "npc":
                    if ($sender->hasPermission($this->getPermission()) === false) {
                        $sender->sendMessage($this->usageMessage);
                        break;
                    }
                    if (count($args) < 2) {
                        $sender->sendMessage("§a/bw npc <shop|upgrade|manager>");
                        break;
                    }

                    switch (($type = strtolower($args[1]))) {
                        case "shop":
                            $shop = new Shop($sender->chunk, Shop::createNBT($sender->getPosition(), $sender->getYaw(), $sender->getPitch()));
                            $shop->spawnToAll();
                            $sender->sendMessage("§r§aShop criado!");
                            break;
                        
                        case "upgrade":
                            $upgrade = new Upgrade($sender->chunk, Upgrade::createNBT($sender->getPosition(), $sender->getYaw(), $sender->getPitch()));
                            $upgrade->spawnToAll();
                            $sender->sendMessage("§r§dUpgrade criado!");
                            break;
                        
                        case "manager":
                            if (isset($args[2])) {
                                $mode = strtolower($args[2]);
                                if ($mode === "solo" or $mode === "duo" or $mode === "squad") {
                                    $manager = new Manager($sender->chunk, Manager::createNBT($sender->getPosition(), $sender->getYaw(), $sender->getPitch(), $sender->getSkinData(), $sender->getSkinId()));
                                    $manager->namedtag->Mode = new StringTag("Mode", $mode);
                                    $manager->spawnToAll();
                                    $sender->sendMessage("§r§aManager criado!");
                                } else {
                                    $sender->sendMessage("§cA npc tem que ser solo, duo ou squad");
                                }
                            } else {
                                $sender->sendMessage("§cInforme o modo da npc solo, dup, squad");
                            }
                            break;
                        
                        case "wins":
                            $wins = new BedWarsWins($sender->chunk, BedWarsWins::createNBT($sender->getPosition(), $sender->getYaw(), $sender->getPitch(), $sender->getSkinData(), $sender->getSkinId(), true));
                            $wins->spawnToAll();
                            $sender->sendMessage("§r§aTop Vitorias criado!");
                            break;
                        
                        default:
                            $sender->sendMessage("§a/bw npc <shop|upgrade|manager|wins>");
                            break ;
                    }
                    break;
                
                case "entrar":
                case "join":
                    if (count($args) < 2) {
                        $canJoin = false;
                        
                        foreach ($this->plugin->arenas as $value) {
                            if ($value->join($sender) === true) {
                                $canJoin = true;
                                break;
                            }
                        }
                        
                        if ($canJoin == false) {
                            $sender->sendMessage("§cThere are no matches available!");
                        }
                    } else {
                        $name = $args[1];
                        
                        foreach ($this->plugin->arenas as $value) {
                            if ($value->getName() == $name) {
                                if ($mt = $value->join($sender) === true) {
                                    break;
                                } else {
                                    $sender->sendMessage("§cIt was not possible to enter this match, full or already started!");
                                }
                                break;
                            }
                        }
                    }
                    break;
                
                case "sair":
                case "quit":
	                $game = $this->plugin->getGame($sender);
	                if ($game !== false) {
	                	$game->quit($sender);
	                }
                break;
                
                case "help":
                    if ($sender->hasPermission($this->getPermission()) === false) {
                        $sender->sendMessage($this->usageMessage);
                        break;
                    }
	                $commands = array(
	                    "criar" => "Para criar um arena",
	                    "npc" => "Para colocar uma npc do bedwars",
	                    "set" => "Para setar as coisas do bedwars",
                        "npc" => "Para setar as npc",
                        "sair" => "Para sair do bedwars"
	                );
	                $sender->sendMessage("§r \n \n §l§a[- BEDWARS -]§r \n \n ");
	                foreach ($commands as $name => $desc) {
	                    $sender->sendMessage("§r§a- §f/{$name}§7 {$desc}");
	                }

                    $sender->sendMessage("§l§eDICA:§r §fComo criar uma arena? sete a loja e o upgrade usando /bw npc, apos use /bw criar e depois termine o resto usando /bw set");
                break;
                
                default:
               		$sender->sendMessage($this->usageMessage);
               	 	break;
            }
        } else {
            $sender->sendMessage($this->usageMessage);
        }
		return true;
	}

}