<?php
	require_once( $GLOBALS['site_root'] . '/includes/models/Chat.inc.php' );
	require_once( $GLOBALS['site_root'] . '/includes/models/User.inc.php' );

	class SuperChatModel {
		private $chatmodel = null;

		public function __construct() {
			$this->chatmodel = new ChatModel();
		}

		public function getVisibleChatrooms() {
			return $this->chatmodel->getVisibleChatrooms();
		}
		
		public function getVisibleChatroomIds() {
			return $this->chatmodel->getVisibleChatroomIds();
		}

		public function getLastChatMessageId() {
			return $this->chatmodel->getLastChatMessageId();
		}

		public function loginUser( $chatroom_id , $user_id ) {
			return $this->chatmodel->loginUser( $chatroom_id , $user_id );
		}
		
		public function keepaliveUser( $user_id ) {
			return $this->chatmodel->keepaliveUser( $user_id );
		}

		public function logoutUser( $chatroom_id , $user_id ) {
			return $this->chatmodel->logoutUser( $chatroom_id , $user_id );
		}

		public function getChatroomUsers( $chatroom_id ) {
			return $this->chatmodel->getChatroomUsers( $chatroom_id );
		}

		public function getChatroomUsersOnMultiRooms( $chatroom_ids ) {
			return $this->chatmodel->getChatroomUsersOnMultiRooms( $chatroom_ids );
		}

		public function postChatroomMessage( $message , $chatroom_id , $message_flags , $poster_user_id = 0 , $target_user_id = 0 , $system = false ) {
			return $this->chatmodel->postChatroomMessage(
				$message,
				$chatroom_id,
				$message_flags,
				$poster_user_id,
				$target_user_id,
				$system );
		}

		public function postChatroomSystemMessage( $message , $chatroom_id , $message_flags , $poster_user_id = 0 , $target_user_id = 0 , $system = false ) {
			return $this->chatmodel->postChatroomSystemMessage(
				$message,
				$chatroom_id,
				$message_flags,
				$poster_user_id,
				$target_user_id,
				$system );
		}

		public function getLatestMessagesForUser( $user_id , $last_message_id ) {
			$query = sprintf( "select * from chat_messages where
				chat_message_id>%d

				order by chat_message_id",
				$last_message_id );
			$ds = FNTH_db_get_resultset( $query );
			if (empty( $ds )) return false;		// nincs meg uj neki szolo uzi
			$retval = array();
			$retval["last_chat_message_id"]=0;
			$retval["messages"]=array();

			// now prepare users
			$user_ids = array();
			foreach ($ds as $row) if (isset( $row["poster_user_id"] )) $user_ids[$row["poster_user_id"]]=true;
			$um = new UserModel();
			$users = $um->getUsersFromUserIds( array_keys( $user_ids ) );
			$usernames = array();
			if (!empty( $users )) {
				foreach ($users as $user) $usernames[$user["user_id"]]=$user["user_name"];
			}
			foreach ($ds as $row) {
				if (isset( $row["poster_user_id"] ))
					$row["poster_user_name"] = $usernames[ $row["poster_user_id"] ];
				$retval["last_chat_message_id"]=$row["chat_message_id"];
				$retval["messages"][]=$row;
			}
			return $retval;
		}
	}

?>
