<?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/Platform/Store/RealmStore.php';
require_once 'Outspark/Platform/Store/RealmInventory.php';
require_once 'Outspark/Platform/Greenspan/Greenspan.php';
require_once 'Outspark/Platform/Greenspan/DataObjects.php';
require_once 'Outspark/UUID.php';
require '../OSKSignedRestResource.inc';

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

class AwardResource extends OSKRestResource
{
	public function dispatch ($req)
	{
		$next = $this;
		$version = $this->getNextRawSegment();

		/*
		 * If version doesn't match, return /user resource
		 */
		if ($version != 'v1') {
			return $this;
		}

		/*
		 * Get the portion after version
		 */
		$this->incrementNextIndex();
		$segment = $this->getNextRawSegment();

		switch ($segment) {
			case 'giveSparkCash':
				$next = new GiveSparkCashResource();
				break;

			case 'givePremiumItems':
				$next = new GivePremiumItemsResource();
				break;
			default:
				// no default action
				break;
		}

		return $next;
	}

	public function GET ($req, $resp)
	{
		/*
		 * Anything not handled under /award is an error.
		 */
		$response = array("stat" => "fail", "data" => array('code' => '404', 'message' => "command not found"));
		$resp->setContent(CTYPE_TEXT, json_encode($response));
		$resp->setStatusCode(REST_STATUS_OK);
	}
}
class GiveSparkCashResource extends OSKSignedRestResource {

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

		$apikey    = $params->getFirst('apikey');
		$userid    = $params->getFirst('userid');
		$sparkcash = $params->getFirst('sparkcash');
		$tag       = $params->getFirst('tag');
		$memo      = $params->getFirst('memo');

		$output = $params->getFirst('output');
		if (empty($output)) {
			$output = 'json';
		}

		$response = array();
		$response['stat'] = "fail"; // fail by default

		if (!empty($userid) && !empty($sparkcash) && !empty($tag) && !empty($memo)) {
			$transaction = false;
			try {
					GSBase::init();
					$fct = new GSFreeCashTransaction();
					$fct->transID = GSTransactionObject::createTransID();
					$fct->userID = $userid;
					$fct->amount = $sparkcash;
					$fct->givenBy = get_class($this);
					$fct->tag = $tag;
					$fct->memo = $memo;
					$fct->save();
					$result = $fct->isPersistent();
					$transaction = $fct->transID;
					
					// set up the response
					$response['stat'] = "ok"; 
					$response['data'] = array("transaction" => $transaction);
			}
			catch (GSException $e) {
				$response['data'] = array('code' => 500, 'message' => $e->getMessage());
			}
		}else{
			$response['data'] = array('code' => REST_STATUS_BAD_REQUEST, 'message' => "Missing required parameters");
		}

		$GLOBALS['logger']->debug("{$outsparkID}: getPurchasedItems : returning ".count($resultItems)." items");

		$json = json_encode($response);

		if ($output == 'text') {
			$resp->setContent(CTYPE_TEXT, $json);
		} else {
			$resp->setContent(CTYPE_JSON, $json);
		}
		$resp->setStatusCode(REST_STATUS_OK);
	}

}

class GivePremiumItemsResource extends OSKSignedRestResource {

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

		$apikey = $params->getFirst('apikey');
		$userid = $params->getFirst('userid');
        $items = $params->getFirst('items');
		$duration = $params->getFirst('duration');

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

		$response = array();
		$response['stat'] = "fail"; // fail by default
		
		if (!empty($userid) && !empty($items)) {
			$transaction = UUID::get(); // just create a new UUID to serve as our transaction
			try{
				// givaway items
				$itemlist = explode(",", str_replace(" ", "", $items)); // remove pesky spaces just in case
				foreach($itemlist as $itempair){
					$i = explode(":", $itempair);
					if(count($i) == 2){
						// index 0 is realm, 1 is itemid
						$this->awardItem($userid, $i[0], $i[1], $transaction, $duration);
					}
				}
				// yay, we did it
				$response['stat'] = 'ok';
				$response['data'] = array('transaction' => $transaction);
			}catch(Exception $e){
				$response['data'] = array('code' => 500, 'message' => 'Unable to award items. Error was: ' . $e->getMessage());
			}
		}else{
			$response['data'] = array('code' => REST_STATUS_BAD_REQUEST, 'message' => "Missing required parameters");
		}

		if (empty($output)) {
			$output = 'json';
		}
		

		$json = json_encode($response);

		if ($output == 'text') {
			$resp->setContent(CTYPE_TEXT, $json);
		} else {
			$resp->setContent(CTYPE_JSON, $json);
		}
		$resp->setStatusCode(REST_STATUS_OK);
	}

	
	private function awardItem($userid, $realm, $itemid, $trans, $duration = false){
		$result = false;
		try {
			$store = new RealmStore($realm);
			$inv = $store->getRealmInventory();
			if ($duration && $duration > 0) {
				$store->awardPerishable($inv->getRealmItem($itemid), $userid, $trans, $duration);
			} else {
				$store->award($inv->getRealmItem($itemid), $userid, $trans);
			}
			unset($store);
			$result = true;
		}
		catch (Exception $e) {
			throw $e;
		}
		return $result;
	}
}

?>
