<?php

/*
 * TODO
 *  Better logging instantiation/customization
 *  Config handling class
 *  Make it easier to set response code and output error
 *  Check user<->game permissions
 */

require 'Outspark/3rdparty/Restafarian/restafarian_common.php';
require_once 'Outspark/Common/KeyMaster/KeyMaster.php';
require_once 'Outspark/Common/GameInfo/GameInfo.php';
require_once 'Outspark/Lib/DBC/GameInfoDBC.php';
require '../OSKSignedRestResource.inc';

// Set up logging
include_once 'Log.php';
$GLOBALS['logger'] = Log::factory('file', '/tmp/osk_error.log', 'StoreResource');
if (is_null($GLOBALS['logger'])) {
	exit("Unable to initiate Logging");
}

class GameResource extends OSKRestResource
{
	public function dispatch ($req)
	{
		$next = $this;
		$version = $this->getNextRawSegment();
		/*
		 * If version doesn't match, return /game resource
		 */
		if ($version != 'v1') {
			return $this;
		}

		/*
		 * Get the portion after version
		 */
		$this->incrementNextIndex();
		$segment = $this->getNextRawSegment();
		switch ($segment) {
			case 'isOpen':
				$next = new GameIsOpenResource();
				break;
            case 'list':
                $next = new GameListResource();
                break;
            case 'clients':
                $next = new ClientListResource();
                break;
            case 'patches':
                $next = new ClientPatchResource();
                break;
			default:
				// no default action
				break;
		}

		return $next;
	}

	public function GET ($req, $resp)
	{
		/*
		 * Anything not handled under /game is an error.
		 */
		$resp->setStatusCode(REST_STATUS_BAD_REQUEST);
		$resp->makeError($this, $resp->getStatusCode(), "Bad Request");
	}
}

class GameIsOpenResource extends OSKRestResource {

	public function GET ($req, $resp)
	{
		
		$params = $req->getUri()->getQueryParams();

		$realm = $params->getFirst('realm');

		$output = $params->getFirst('output');
		if (empty($output)) {
			$output = 'text'; // text by default for simplicity
		}

		if (empty($realm)) {
			$resp->setStatusCode(REST_STATUS_BAD_REQUEST);
			$resp->makeError($this, $resp->getStatusCode(), 'Bad request');
			return;
		}

		$gi = GameInfo::fetch();
		$result = 1;
		if( isset($gi[$realm]) ){
			$result = $gi[$realm]['isopen'];
		}
        
		if ($output == 'text') {
			$resp->setContent(CTYPE_TEXT, $result);
		} else {
			$json = json_encode(array('open' => $result));
			$resp->setContent(CTYPE_JSON, $json);
		}
		$resp->setStatusCode(REST_STATUS_OK);
	}

}

class GameListResource extends OSKRestResource {

	public function GET ($req, $resp)
	{
		
		$params = $req->getUri()->getQueryParams();

		$output = $params->getFirst('output');
		if (empty($output)) {
			$output = 'text'; // text by default for simplicity
		}


		$gi = GameInfo::fetch();
		$result = array();
        foreach(array_keys($gi) as $realm){
            if( $gi[$realm]['isgame'] == 1 && $gi[$realm]['installer']){
                $r = $realm == "sos"?"solstice" : $realm;
                $r = $realm == "propow"?"projectpowder" : $realm;
                $result[$r] = array(
                    "realm" => $r,
                    "name" => $gi[$realm]['displayName'],
                    "gameweb" => $gi[$realm]['gameweb'],
                    "launcher" => $gi[$realm]['launcher'],
                    "installer" => $gi[$realm]['installer'],
                    "version" => $gi[$realm]['version'],
                    "clientsize" => $gi[$realm]['clientsize'],
                    "peerinstaller" => $gi[$realm]['peerinstaller'],
                );
            }
        }
        $json = json_encode($result);
		if ($output == 'text') {
			$resp->setContent(CTYPE_TEXT, $json);
		} else {
			$resp->setContent(CTYPE_JSON, $json);
		}
		$resp->setStatusCode(REST_STATUS_OK);
	}

}

class ClientListResource extends OSKRestResource {

	public function GET ($req, $resp)
	{
		
		$params = $req->getUri()->getQueryParams();

		$output = $params->getFirst('output');
		if (empty($output)) {
			$output = 'text'; // text by default for simplicity
		}
        
        // optional parameter
        $appid = $params->getFirst('appid');
		if (empty($appid)) {
			$appid = false; // this param is optional
		}

		$dbc = new GameInfoDBC();
        $clientDB = $dbc->getPDO();
        
        $result = array();
        $params = array();
        $query = "SELECT * FROM clients_versions WHERE 1=1 ";
        if($appid){
            // we have an appid, so limit the result set
            $query .= " AND appid=:appid";
            $params[":appid"] = $appid;
        }
        $query .= " ORDER BY title";

        $stmt = $clientDB->prepare($query);
        $stmt->execute($params);
        foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $app){
            $result[$app['appid']] = $app;
        }
        
        $json = json_encode($result);
		if ($output == 'text') {
			$resp->setContent(CTYPE_TEXT, $json);
		} else {
			$resp->setContent(CTYPE_JSON, $json);
		}
		$resp->setStatusCode(REST_STATUS_OK);
	}

}

class ClientPatchResource extends OSKRestResource {

    private $pdo = null;
	public function GET ($req, $resp)
	{
		
		$params = $req->getUri()->getQueryParams();

		$output = $params->getFirst('output');
		if (empty($output)) {
			$output = 'text'; // text by default for simplicity
		}
        
        // optional parameter
        $appid = $params->getFirst('appid');
		if (empty($appid)) {
			$appid = false; // this param is optional
		}
        $version = $params->getFirst('version');
        
		if (empty($version)) {
			$resp->setStatusCode(REST_STATUS_BAD_REQUEST);
			$resp->makeError($this, $resp->getStatusCode(), 'Bad request');
			return;
		}
        $version = explode(".", $version);
	while(count($version) > 3){
		array_pop($version);
	}
        for($i = 0; $i < count($version); $i++){
			$version[$i] = (string)sprintf("%04d", $version[$i]);
		}
        $version = implode(".", $version);

		$dbc = new GameInfoDBC();
        $this->pdo = $dbc->getPDO();
        
        $result = array();
        $params = array();

		$patches = $this->getPatch($appid, $version);
        $json = json_encode($patches);
		if ($output == 'text') {
			$resp->setContent(CTYPE_TEXT, $json);
		} else {
			$resp->setContent(CTYPE_JSON, $json);
		}
		$resp->setStatusCode(REST_STATUS_OK);
	}
    
    function getPatch($appid, $current_version){
        $patches = array();
        $params[":current_version1"] = $current_version;
        $params[":current_version2"] = $current_version;
        $params[":appid1"] = $appid;
        $params[":appid2"] = $appid;
        $sql = "SELECT * FROM clientpatch_versions where from_version=:current_version1 and to_version in (SELECT MAX(to_version) from clientpatch_versions where from_version=:current_version2 and appid=:appid1 AND released< NOW()) and appid=:appid2 AND released < NOW()";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $row){
            if( isset($row['url']) ){
                $patches=array_merge(array($row), $this->getPatch($appid, $row['to_version']));
            }
        }
        return $patches;
  }

}

?>
