<?php

namespace Juqn;

use pocketmine\Server;

use pocketmine\Player;

use pocketmine\math\Vector3;

use pocketmine\level\particle\FloatingTextParticle;

use pocketmine\event\Listener;
use pocketmine\event\player\PlayerJoinEvent;

class Mod_TopModule implements Listener {

    /** @var \SQLite3 */
    private $db;

    /** @var FloatingTextParticle */
    private $ft;

    /** @var string */
    private $format;

    /** @var string */
    private $level;

    /** @var array */
    private $pks;

    public function __construct($plugin) {
        $file = 'mod_top.yml';
        $path = $plugin->getDataFolder() . $file;
        if (!file_exists($path)) {
            file_put_contents($path, $plugin->getResource($file));
        }

        $this->db = new \SQLite3($plugin->getDataFolder() . 'mod_top.db');
        $this->db->query('CREATE TABLE IF NOT EXISTS sw_top (
            player TEXT NOT NULL,
            score INTEGER NOT NULL,
            UNIQUE(player)
        )');

        $settings = yaml_parse_file($path);
        
        $p = explode(',', $settings['text-pos']);
        $pos = new Vector3((int) array_shift($p), (int) array_shift($p), (int) array_shift($p));
        $this->level = implode(',', $p);

        $this->format = $settings['line'];

        $this->ft = new FloatingTextParticle($pos, '', $settings['title']);
        $this->reloadData();

        $plugin->getServer()->getPluginManager()->registerEvents($this, $plugin);
    }

    public function onWin(Player $player) {
        $player = strtolower($player->getName());

        $query = $this->db->prepare('INSERT OR IGNORE INTO sw_top VALUES(:player, 0)');
        $query->bindValue(':player', $player, \SQLITE3_TEXT);
        $query->execute();

        $query = $this->db->prepare('UPDATE sw_top SET score = score + 1 WHERE player = :player');
        $query->bindValue(':player', $player, \SQLITE3_TEXT);
        $query->execute();
    }

    public function reloadData() {
        $num = 0;
        $text = '';

        $result = $this->db->query('SELECT * FROM sw_top ORDER BY score DESC LIMIT 10');
        $data = $result->fetchArray(\SQLITE3_ASSOC);
        while ($data) {
            $num++;

            $text .= strtr($this->format, [
                '%NUM%'    => (string) $num,
                '%PLAYER%' => $data['player'],
                '%COUNT%'  => (string) $data['score']
            ]);

            $data = $result->fetchArray(\SQLITE3_ASSOC);
            if ($data) {
                $text .= "\n";
            }
        }

        $this->ft->setText($text);
        
        $pks = $this->ft->encode();
        if (!is_array($pks)) {
            $pks = [$pks];
        }
        $this->pks = $pks;

        foreach (Server::getInstance()->getOnlinePlayers() as $player) {
            $this->sendTextParticle($player);
        }
    }

    public function onJoin(PlayerJoinEvent $e) {
        $this->sendTextParticle($e->getPlayer());
    }

    private function sendTextParticle(Player $player) {
        foreach ($this->pks as $pk) {
            $player->dataPacket($pk);
        }
    }

}
