<?php
	
	namespace Api\Libs\Rcon\Games;
	
	use Api\Libs\Rcon\BaseRcon;
	use Api\Libs\Rcon\IRcon;
	use Exception;
	use xPaw\SourceQuery\Exception\AuthenticationException;
	use xPaw\SourceQuery\Exception\InvalidArgumentException;
	use xPaw\SourceQuery\Exception\InvalidPacketException;
	use xPaw\SourceQuery\Exception\SocketException;
	use xPaw\SourceQuery\SourceQuery;
	
	class Minecraft extends BaseRcon implements IRcon
	{
		public function __construct($host, $port, $password) {
			parent::__construct($host, $port, $password);
			$this->socket = new SourceQuery();
		}
		
		/**
		 * @throws InvalidPacketException
		 * @throws AuthenticationException
		 * @throws SocketException
		 * @throws InvalidArgumentException
		 */
		public function connect(): void
		{
			$this->socket->Connect( $this->host, $this->port);
			$this->socket->SetRconPassword($this->password);
		}
		
		public function disconnect(): bool
		{
			$this->socket->Disconnect();
			$this->socket = null;
			return true;
		}
		
		public function checkConnection(): bool
		{
			try {
				$this->connect();
				$this->sendCommand("say Test!");
				$this->disconnect();
				return true;
			} catch (Exception $e) {
				return false;
			}
		}
		
		/**
		 * @throws SocketException
		 * @throws InvalidPacketException
		 * @throws AuthenticationException
		 */
		public function sendCommand(string $command, bool $response = false)
		{
			$result = $this->socket->Rcon($command);
			if ($response) {
				return $result;
			}
			return true;
		}
	}