<?php

namespace bridge;

use pocketmine\plugin\PluginBase;
use pocketmine\event\Listener;

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

use pocketmine\utils\Config;
use pocketmine\Player;

use bridge\task\BridgeTask;
use bridge\utils\arena\Arena;
use bridge\utils\arena\ArenaManager;

class Main extends PluginBase{
	
	public $arenas = [];
	
	private $pos1 = [];
	private $pos2 = [];
	    public $MOD_top_module;
	private $pos = [];
	private $spawn1 = [];
	private $spawn2= [];
	private $respawn1= [];
	private $respawn2= [];
	
	public function onEnable(){
		$this->initResources();
		$this->initArenas();
		        $this->MOD_top_module = new Mod_TopModule($this);
		$this->getServer()->getScheduler()->scheduleRepeatingTask(new BridgeTask($this), 20);
		$this->getServer()->getPluginManager()->registerEvents(new Arena($this), $this);
	}
	
	public function onDisable(){
		$this->close();
	}
	
	private function initResources(){
		@mkdir($this->getDataFolder());
		@mkdir($this->getDataFolder() . "mapas/");
		@mkdir($this->getDataFolder() . "arenas/");
	}
	
	private function initArenas(){
		$src = $this->getDataFolder() . "arenas/";
		$count = 0;
		foreach(scandir($src) as $file){
			if($file !== ".." and $file !== "."){
				if(file_exists("$src" . $file)){
					$data = (new Config("$src" . $file, Config::YAML))->getAll();
					if(!isset($data["name"])){
						@unlink("$src" . $file);
						continue;
					}
					$this->arenas[strtolower($data["name"])] = new ArenaManager($this, $data);
					$count++;
				}
			}
		}
		return $count;
	}
	
	public function getPlayerArena(Player $p){
		$arenas = $this->arenas;
		if(count($arenas) <= 0){
			return null;
		}
		foreach($arenas as $arena){
			if($arena->isInArena($p)){
				return $arena;
			}
		}
		return null;
	}
	
	public function updateArenas($value = false){
		if(count($this->arenas) <= 0){
			return false;
		}
		foreach($this->arenas as $arena){
			$arena->onRun($value);
		}
	}
	
	private function close(){
		foreach($this->arenas as $name => $arena){
			$arena->close();
		}
	}
	
	public function join($player, $mode = "solo"){
		foreach($this->arenas as $name => $arena){
			if($arena->getData()["mode"] == $mode){
				if($arena->join($player)){
					return true;
				}
			}
		}
		return false;
	}
	
	public function createBridge($name, $p, $pos1, $pos2, $spawn1, $spawn2, $respawn1, $respawn2, $pos, $mode = "solo"){
		$src = $this->getDataFolder();
		if(file_exists($src . "arenas/" . strtolower($name) . ".yml")){
			$p->sendMessage("§cJá existe uma Arena com este Nome!");
			return false;
		}
		$config = new Config($src . "arenas/" . $name . ".yml", Config::YAML);
		
		$data = ["name" => $name, "mode" => $mode, "world" => $p->getLevel()->getName(), "local-de-espera" => $pos, "pos1" => $pos1, "pos2" => $pos2, "spawn1" => $spawn1, "spawn2" => $spawn2, "respawn1" => $respawn1, "respawn2" => $respawn2];
		
		$arena = new ArenaManager($this, $data);
		
		$this->arenas[strtolower($name)] = $arena;
				
		$config->setDefaults($data);
		$config->save();
		return true;
	}
	
	public function deleteBridge($name){
		if(file_exists($src . "arenas/" . strtolower($name) . ".yml")){
			if(unlink($src . "arenas/" . strtolower($name) . ".yml")){
				if(isset($this->arenas[strtolower($name)])){
					unset($this->arenas[strtolower($name)]);
				}
				return true;
			}
		}
		return false;
	}
	
	public function onCommand(CommandSender $sender, Command $cmd, $label, array $args){
		if(strtolower($cmd->getName()) == "bridge"){
			if(!$sender instanceof Player){
				return true;
			}
			if(isset($args[0])){
				switch(strtolower($args[0])){
					case "pos1":
					if(!$sender->hasPermission("bridge.cmd")){
						$sender->sendMessage("/bridge");
						return true;
					}
					$x = $sender->getFloorX();
					$y = $sender->getFloorY();
					$z = $sender->getFloorZ();
					$this->pos1[$sender->getName()] = ["x" => $x, "y" => $y, "z" => $z];
					$sender->sendMessage("§a1 точка устоновлена на кордах §eX:§6 $x §eY: §6$y §eZ: §6$z");
					break;
					case "pos2":
					if(!$sender->hasPermission("bridge.cmd")){
						$sender->sendMessage("§a2 точка устоновлена, §1/bridge help");
						return true;
					}
					$x = $sender->getFloorX();
					$y = $sender->getFloorY();
					$z = $sender->getFloorZ();
					$this->pos2[$sender->getName()] = ["x" => $x, "y" => $y, "z" => $z];
					$sender->sendMessage("§a2 точка устоновлена на кордах §eX:§6 $x §eY: §6$y §eZ: §6$z");
					break;
					case "spawn1":
					if(!$sender->hasPermission("bridge.cmd")){
						$sender->sendMessage("§a1 точка спавна устоновлена команды, §1/bridge help");
						return true;
					}
					$x = $sender->getFloorX();
					$y = $sender->getFloorY();
					$z = $sender->getFloorZ();
					$this->spawn1[$sender->getName()] = ["x" => $x, "y" => $y, "z" => $z];
					$sender->sendMessage("§aВозрождение устоновнено на корды §eX:§6 $x §eY: §6$y §eZ: §6$z");
					break;
					case "spawn2":
					if(!$sender->hasPermission("bridge.cmd")){
						$sender->sendMessage("§a2 точка спавна команды устоновлена, §1/bridge help");
						return true;
					}
					$x = $sender->getFloorX();
					$y = $sender->getFloorY();
					$z = $sender->getFloorZ();
					$this->spawn2[$sender->getName()] = ["x" => $x, "y" => $y, "z" => $z];
					$sender->sendMessage("§aВозрождение устоновнено на корды §eX:§6 $x §eY: §6$y §eZ: §6$z");
					break;
					case "respawn1":
					if(!$sender->hasPermission("bridge.cmd")){
						$sender->sendMessage("§a1 точка респавна устоновлена");
						return true;
					}
					$x = $sender->getFloorX();
					$y = $sender->getFloorY();
					$z = $sender->getFloorZ();
					$this->respawn1[$sender->getName()] = ["x" => $x, "y" => $y, "z" => $z];
					$sender->sendMessage("§a1 точка респавна устоновлена на кординатах §eX:§6 $x §eY: §6$y §eZ: §6$z");
					break;
					case "respawn2":
					if(!$sender->hasPermission("bridge.cmd")){
						$sender->sendMessage("§a2 точка респавна устоновлена");
						return true;
					}
					$x = $sender->getFloorX();
					$y = $sender->getFloorY();
					$z = $sender->getFloorZ();
					$this->respawn2[$sender->getName()] = ["x" => $x, "y" => $y, "z" => $z];
					$sender->sendMessage("§a2 точка респавна устоновлена на кординатах §eX:§6 $x §eY: §6$y §eZ: §6$z");
					break;
					case "spawn":
					if(!$sender->hasPermission("bridge.cmd")){
						$sender->sendMessage("§aТочка ожидания устоновлена");
						return true;
					}
					$x = $sender->getFloorX();
					$y = $sender->getFloorY();
					$z = $sender->getFloorZ();
					$this->pos[$sender->getName()] = ["x" => $x, "y" => $y, "z" => $z, "level" => $sender->getLevel()->getName()];
					$sender->sendMessage("§aТочка ожидания устоновлена §eX:§6 $x §eY: §6$y §eZ: §6$z");
					break;
					case "criar":
					if(!$sender->hasPermission("bridge.cmd")){
						$sender->sendMessage("§aИспользуй §1/bridge criar");
						return true;
					}
					if(isset($args[1])){
						$name = $sender->getName();
						if(!isset($this->pos1[$name]) or !isset($this->pos2[$name])){
							$sender->sendMessage("§aОшибка 1 и 2 позиции, §1/bridge help");
							return true;
						}
						if(!isset($this->spawn1[$name]) or !isset($this->spawn2[$name])){
							$sender->sendMessage("§a1 и 2 место спавна не утоновлено, §1/bridge help");
							return true;
						}
						if(!isset($this->respawn1[$name]) or !isset($this->respawn2[$name])){
							$sender->sendMessage("§a1 и 2 место респавна не утоновлено, §1/bridge help");
							return true;
						}
						if(!isset($this->pos[$name])){
							$sender->sendMessage("§aМесто ожидания не утоновлено, §1/bridge help");
							return true;
						}
						$level = $sender->getLevel();
						if(strlen($args[1]) > 15){
							$sender->sendMessage("§aИмя арена должна содержать не более 15 букв");
							return true;
						}
						$mode = "solo";
						if(isset($args[2])){
							switch(strtolower($args[2])){
								case "solo":
								case "team":
								case "squad":
								$mode = strtolower($args[2]);
								break;
								default:
								$sender->sendMessage("§aВыбери режим §esolo/team/squad");
								return true;
							}
						}
						if($this->createBridge($args[1], $sender, $this->pos1[$name], $this->pos2[$name], $this->spawn1[$name], $this->spawn2[$name], $this->respawn1[$name], $this->respawn2[$name], $this->pos[$name], $mode)){
							$sender->sendMessage("§aАрена §f" . $args[1] . "§a создана");
						}
					} else {
						$sender->sendMessage("§aИспользуйте §1/bridge criar (имя) (режим)");
						return true;
					}
					break;
					case "deletar":
					if(!$sender->hasPermission("bridge.cmd")){
						$sender->sendMessage("§aИспользуй §1/bridge deletar");
						return true;
					}
					if(isset($args[1])){
						if($this->deleteBridge($args[1])){
							$sender->sendMessage("§aКарта §b" . $args[1] . "§a успешно удалена");
						} else {
							$sender->sendMessage("§aКарта не может быть удалена т.к не верное название");
						}
					}
					break;
					case "entrar":
					$mode = "solo";
					if(isset($args[1])){
						switch(strtolower($args[1])){
							case "solo":
							case "team":
							case "squad":
							$mode = strtolower($args[1]);
							break;
							default:
							return true;
						}
					}
					if($this->join($sender, $mode)){
					} else {
						$sender->sendMessage("§c» §fAll maps are occupied!");
					}
					break;
					default:
					$sender->sendMessage("§aИспользуй §1/bridge help");
					break;
				}
			} else {
				$sender->sendMessage("§aИспользуй §1/bridge help");
			}
		}
	}
}