<?php

namespace PLevel;

use pocketmine\plugin\PluginBase;
use pocketmine\event\player\PlayerDeathEvent as died;
use pocketmine\Player;
use pocketmine\command\Command;
use pocketmine\command\CommandSender;
use pocketmine\utils\Config;
use pocketmine\event\Listener;
use pocketmine\event\player\{PlayerRespawnEvent, PlayerJoinEvent};
use pocketmine\event\entity\EntityDamageByEntityEvent;
class Main extends PluginBase implements Listener{
	
	public function onEnable(){
     $this->getServer()->getPluginManager()->registerEvents($this, $this);
$this->cfg();
	}

public function cfg(){
$p = $this->getDataFolder();
@mkdir($p);
$cfg = new Config("{$p}xp.yml", Config::YAML);
return $cfg;
}

public function addXp($p, $nxp){
$cfg = $this->cfg();
$oxp = $this->getXp($p);
$xp = $nxp + $oxp;
$this->getServer()->getPluginManager()->callEvent($e = new PlayerAddXpLevelEvent($p, $nxp, $xp));
if($e->isCancelled()) return;
if($p instanceof Player){
$n = strtolower($p->getName());
}else{
$n = strtolower($p);
}
$cfg->set($n, $xp);
$cfg->save();
}

public function getXp($p){
$cfg = $this->cfg();
if($p instanceof Player){
$n = strtolower($p->getName());
}else{
$n = strtolower($p);
}
if(!$cfg->exists($n)) return 0;
return $cfg->get($n);
}

public function getLvl($p){
$xp = $this->getXp($p);
$lvl = $xp / 100;
$lvl++;
$lvl = explode(".", $lvl)[0];
return $lvl;
}

public function onJoin(PlayerJoinEvent $ev){
$p = $ev->getPlayer();
$lev = $this->getLvl($p);
$p->setExpLevel($lev);
}

public function onExp(PlayerAddXpLevelEvent $e){
$p = $e->getPlayer();
$lev = $this->getLvl($p);
$p->setExpLevel($lev);
}

public function onRespawn(PlayerRespawnEvent $eve){
$p = $eve->getPlayer();
$leve = $this->getLvl($p);
$p->setExpLevel($leve);
}

public function onDied(died $e){
$p = $e->getPlayer();
$c = $p->getLastDamageCause();
			if($c instanceof EntityDamageByEntityEvent){
				$d = $c->getDamager();
if($d instanceof Player){
$this->addXp($d, 1);
}
}
}

public function strLvl($p){
$lvl = $this->getLvl($p);
$l = $this->getXp($p) % 100;
return "§e{$lvl} §8[§e{$l}§8/§e100§8]";
}

public function onCommand(CommandSender $p, Command $cmd, $label, array $args){
		if($cmd == "lvl"){
return $p->sendMessage("§a» §fYour level: {$this->strLvl($p)}");
}

if($cmd == "toplvl"){
$cfg = $this->cfg();
$a = $cfg->getAll();
asort($a);
$max = 0;
foreach ($a as $aa){
$max++;
}
$p->sendMessage("§a» §fTop players by level:");
$pl = 0;
while($pl <= 5){

$this->getWiner($max, $p, $pl);
$pl++;
$max = $max - 1;

	}
}
}



public function getWiner($max, $p, $m){
$cfg = $this->cfg();
$a = $cfg->getAll();
asort($a);
$send = 0;

foreach ($a as $key => $value) {
if($send == $max){
$max = $max-1;
$p->sendMessage("§e#{$m}, §f{$key} §7» {$this->strLvl($key)}");

}
$send++;
}
}
}