<?php

namespace Juqn\Arena;

use Juqn\Loader;
use pocketmine\Player;
use pocketmine\utils\Config;

class ArenaManager {
	
	public $plugin;
	
	public $arenas = [];
	
	public $sessions = [];
	
	public function __construct(Loader $plugin){
		$this->plugin = $plugin;

		$this->registerArenas();
	}
	
	public function getPlugin(){
		return $this->plugin;
	}
	
	public function getServer(){
		return $this->getPlugin()->getServer();
	}
	
	public function getArenas(){
		return $this->arenas;
	}
	
	public function registerArenas(){
		$folder = $this->getPlugin()->getDataFolder()."Arenas/";
		if(empty($folder)) return false;
		$scan = scandir($folder);
		foreach($scan as $files){
			if($files !== ".." and $files !== "."){
				$config = new Config($folder.$files, Config::YAML);
				if(!$config->exists('name')){
				    unlink($folder.$files);
				    $name = str_replace(".yml", "", $files);
				    if(file_exists($this->getPlugin()->getDataFolder()."Maps/".$name.".zip")){
				        unlink($this->getPlugin()->getDataFolder()."Maps/".$name.".zip");
                    }
                }
                $all = $config->getAll();
				$this->getServer()->loadLevel($all['level-name']);
				$this->arenas[$all['name']] = new Arena($all);
			}
		}
		return true;
	}
	
	public function createArena(Player $player, $name, $slots, $level){
		if(file_exists($this->getPlugin()->getDataFolder()."Arenas/".$name.".yml")){
			return false;
		}
		$array = [
			"name" => $name,
			"slots" => $slots,
			"level-name" => $level,
			"spawns" => []
		];
		$this->sessions[$player->getName()] = $array;
		return true;
	}
	
	public function registerArena($playerName){
		if(isset($this->sessions[$playerName])){
			$array = $this->sessions[$playerName];
			$config = new Config($this->getPlugin()->getDataFolder()."Arenas/".$array["name"].".yml", Config::YAML);
			if(count($array['spawns']) == $array['slots']){
				$config->setDefaults($array);
				$config->save();
				$this->arenas[$array["name"]] = new Arena($array);
				unset($this->sessions[$playerName]);
			}
			return true;
		}
		return false;
	}
	
	public function joinArena(Player $player){
		if(count($this->arenas) <= 0) return false;
		foreach($this->arenas as $arena){
			if($arena->join($player)){
				return true;
			}
		}
		return false;
	}
	
	public function inArena(Player $player){
		if(count($this->arenas) <= 0){
			return false;
		}
		foreach($this->arenas as $arena){
			if($arena->getPlayer($player->getName())){
				return $arena;
			}
		}
		return false;
	}
}