<?php


class q3query_log extends q3query {
    private $log;
    private $logfile;

    public function __construct($address, $port, $logfile) {
        $this->logfile = $logfile;

        parent::__construct($address, $port);

    }

    public function connect() {
        parent::connect();

        $this->writeLog("=================");
        $this->writeLog("Connection opened");
    }

    public function rcon($str) {
    	$this->writeLog(" Input: $str");
    	$s =  parent::rcon($str);

    	$lines = explode("\n", $s);
		foreach ($lines as $value) {
			$this->writeLog("Output: $value");
		}

		return $s;
    }


    public function quit() {
        parent::quit();
    	if (is_resource($this->log)) {
		    $this->writeLog("Connection Closed");
			$this->writeLog("=================");
    		fclose($this->log);
    	}
    }

    private function writeLog($line) {
        if (!is_resource($this->log)) {
            $this->log = fopen($this->logfile, "a");
        }
    	$timestamp = date("[d.m.y H:i:s] ");
    	fputs($this->log, $timestamp . $line . "\r\n");
    }

    public function __destruct() {
        fclose($this->log);
    }


}