<?php
class cFbManager extends cBase {
	var $fb;
	var $user;
	
	function cmp_hash( $fbid, $game, $value, $hash ) {
		$str = 'joju_mo_'.$fbid.'_'.$game.'_'.$value;
		$md5 = md5( $str );
		
		trace( "hashing string: $str" );
		trace( "cmp_hash: $hash == $md5 ".( $hash == $md5 ? 'true' : 'false' ) );
		
		return $hash == $md5 ? true : false;
	}
	
	function cFbManager( $requireframe=true, $init_fb=true, $tabinit=0 ) {
		if ( $init_fb == true ) {
			parent::cBase($tabinit);
			$this->fb = new Facebook(FB_APIKEY, FB_APPSECRET);
			
			if ( $requireframe == true )
				$this->fb->require_frame();
			
			$this->create_user();
		}
	}
	
	function create_user() {
		$user_id = $this->fb->require_login();
		$user_info = $this->fb->api_client->users_getInfo($user_id, 'uid, name, pic');
		$user_data = $user_info[0];
		
		$this->user = new cFbUser( $user_data );
		
		$this->create_db_user();
	}
	
	function create_db_user() {
		$admin = new cAdminUser();
		$admin->user_add( $this->user->fbid(), $this->user->name() );
		$this->pl( $admin->data );
	}
	
	function get_user() {
		return $this->user;
	}
	
	function show() {
		$this->pl( obj_render ( new cPara("Hello, ".$this->user->name()." ( ".$this->user->fbid()." ).") ) );
		cPage::addheaddata( get_unity_header() );
		$this->pl( add_unity3d( PAGE.'mo.unity3d', '700', '525' ) );
	}
	
	function execute( $exec, $fbid, $game, $hash, $var ) {
		trace( "execute: $exec $fbid $hash $game $var" );
		
		if ( $this->cmp_hash( $fbid, $game, $value, $hash ) ) {
			switch ( $exec ) {
				case 0:
					$this->pd( 'pong' );
					break;
				case 1:
					$this->get_fb_user_data();
					break;
				case 2:
					$this->high_score_submit( $fbid, $hash, $game, $var );
					break;
			}
		}
	}
	
	function get_fb_user_data() {
		$this->pd( $this->user->fbid().';'.$this->user->uid().';'.$this->user->name().';'.$this->user->pic() );
	}
	
	function high_score_submit( $fbid, $hash, $game, $value ) {
		trace( "submit_high_score: $fbid $game $value $hash" );
		
		if ( intval( $value ) > 0 && $this->user->uid() == $fbid && $this->cmp_hash( $fbid, $game, $value, $hash ) ) {
			$admin = new cAdminUser();
			$admin->user_submit_score( $fbid, $game, $value );
		}
	}
	
	/*
	function high_scores_get() {
		$friends = $this->fb->friends_get();
		$frd = '';
		
		foreach ( $friends as $friend ) {
			$frd += ''
		}
		
		$sql = 'SELECT user_name, user_fbid, ghs_score FROM user, game_hs WHERE ghs_uid=user_uid AND ghs_gameid=gameId '.$friends.' ORDER BY ghs_score DESC LIMIT 10;';
	}
	*/
}
?>