<?php
	require_once( $GLOBALS["site_root"] . "/includes/widgets/Widget.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/SelectedUsers.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/Users.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/urlgen/Member.inc.php" );

	class UserNameTag extends Widget {
		protected $iUserId = 0;
		protected $bSelected = false;
		protected $sPrefix = "";
		protected $sPostfix = "";

		protected function initNameTagCache() {
			if (!isset( $GLOBALS["UserNameTagCache"] )) $GLOBALS["UserNameTagCache"]=array();
		}

		public function setPrefix( $v ) { $this->sPrefix = $v; }

		protected function loadCache() {
			if (isset( $GLOBALS["UserNameTagCacheData"] )) return;
			$this->initNameTagCache();
			$usersmodel = new UsersModel();
			$ds = $usersmodel->getMembersFromUserIds( array_keys( $GLOBALS["UserNameTagCache"] ) , true , $GLOBALS["language"] );
			$GLOBALS["UserNameTagCacheData"]=array();
			$murl = new MemberURL();
			$now = fo3_date( "Y-m-d H:i:s" );
			foreach ($ds as $row) {
				$row["active"]=($row["expires_tstamp"]>$now);
				$row["url"]=$murl->renderURLFromMember( $row );
				$GLOBALS["UserNameTagCacheData"][$row["user_id"]]=$row;
			}
		}

		protected function setNameTagUserId( $user_id ) {
			$this->initNameTagCache();
			$GLOBALS["UserNameTagCache"][$user_id]=true;
		}

		protected function unsetNameTagUserId( $user_id ) {
			$this->initNameTagCache();
			unset( $GLOBALS["UserNameTagCache"][$user_id] );
		}

		public function setId( $user_id ) {
			if ($this->iUserId) $this->unsetNameTagUserId( $this->iUserId );
			$this->iUserId = $user_id;
			$this->setNameTagUserId( $this->iUserId );
		}

		protected function generateLangDefs() {
			fo3_add_js_langdef( "usernametag_add" );
			fo3_add_js_langdef( "usernametag_del" );
		}

		public function render() {
			if ($this->sRendered) return $this->sRendered;
			$this->generateLangDefs();
			$selusers = new SelectedUsersModel();
			$this->bSelected = $selusers->isUserSelected( $this->iUserId );
			FNTHPage::addUniquePageFullInit( sprintf( "InitUserNameTag( '%s' , %d , %d );\n",
				$this->getId(),
				$this->iUserId,
				$this->bSelected ));
			$this->loadCache();
			$this->setParam( "user_id" , $this->iUserId );
			$this->setParam( "datas" , $GLOBALS["UserNameTagCacheData"][$this->iUserId] );
			$this->setParam( "sPrefix" , $this->sPrefix );
			$this->setParam( "sPostfix" , $this->sPostfix );
			$this->setParam( "is_selected" , $this->bSelected );
			return parent::render();
		}
	}

?>
