<?php

namespace Plugin\Tasks;

use pocketmine\scheduler\PluginTask;
use pocketmine\Server;

use Plugin\ServerAuth;

class MySQLTask extends PluginTask {
	
    public function __construct(ServerAuth $plugin){
    	parent::__construct($plugin);
        $this->plugin = $plugin;
        $this->plugin = $this->getOwner();
    }
    
    public function onRun($tick){
    	$cfg = $this->plugin->getConfig()->getAll();
    	if($cfg["use-mysql"] == true){
    		if(ServerAuth::getAPI()->getDatabase() == false){
    			$check = ServerAuth::getAPI()->checkDatabase($cfg["mysql"]["host"], $cfg["mysql"]["port"], $cfg["mysql"]["username"], $cfg["mysql"]["password"]);
    			if($check[0]){
    				Server::getInstance()->getLogger()->info($this->plugin->translateColors("&", ServerAuth::PREFIX . $this->plugin->chlang["mysql-restored"]));
    				ServerAuth::getAPI()->initializeDatabase($cfg["mysql"]["host"], $cfg["mysql"]["port"], $cfg["mysql"]["username"], $cfg["mysql"]["password"], $cfg["mysql"]["database"], $cfg["mysql"]["table_prefix"]);
    				ServerAuth::getAPI()->mysql = true;
    			}
    		}elseif(!ServerAuth::getAPI()->getDatabase()->ping()){
    			$check = ServerAuth::getAPI()->checkDatabase($cfg["mysql"]["host"], $cfg["mysql"]["port"], $cfg["mysql"]["username"], $cfg["mysql"]["password"]);
    			if($check[0]){
    				Server::getInstance()->getLogger()->info($this->plugin->translateColors("&", ServerAuth::PREFIX . $this->plugin->chlang["mysql-restored"]));
    				ServerAuth::getAPI()->initializeDatabase($cfg["mysql"]["host"], $cfg["mysql"]["port"], $cfg["mysql"]["username"], $cfg["mysql"]["password"], $cfg["mysql"]["database"], $cfg["mysql"]["table_prefix"]);
    				ServerAuth::getAPI()->mysql = true;
    			}
    		}
    	}else{
    		ServerAuth::getAPI()->mysql = false;
    	}
    }
}
?>
