<?php
	require_once( $GLOBALS["site_root"]."/includes/widgets/Widget.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/MyUser.inc.php" );
	require_once( $GLOBALS["site_root"]."/includes/models/SuperChat.inc.php" );

	class ChatPanel extends Widget {
		protected $chat_model;

		public function handleEvents() {
			if (!isset( $this->aP["inajax"] ))
				return parent::handleEvents();
			if (!isset( $this->aP["ajaxevent"] )) 
				return parent::handleEvents();
			switch ($this->aP["ajaxevent"]) {
			case "post_system_command":
				$mum = new MyUserModel();
				switch ($this->aP["command"]) {
				case "login":
					$retval = $this->chat_model->loginUser( $this->aP["chatroom_id"], $mum->getLoggedinUserId() );
					FNTH_echo_json_response( $retval , 0 , "fo3_exit" );
					break;
				case "logout":
					$retval = $this->chat_model->logoutUser(
						$this->aP["chatroom_id"],
						$mum->getLoggedinUserId() );
					break;
				}
				break;
			case "post_chatroom_message":
				$mum = new MyUserModel();
				$retval = $this->chat_model->postChatroomMessage(
					$mum->getLoggedinUserId(),
					$this->aP["message"],
					$this->aP["chatroom_id"] );
				FNTH_echo_json_response( $retval , 0 , "fo3_exit" );
				break;
			/*
			case "get_new_messages":
				// not used - moved to
				$retval = array();
				$retval["messages"]=$this->chat_model->getChatMessages( $this->aP["last_chat_message_id"] );
				$mum = new MyUserModel();
				$this->chat_model->keepaliveUser( $mum->getLoggedinUserId() );
				FNTH_echo_json_response( $retval , 0 , "fo3_exit" );
				break;
			*/
			case "get_online_members":
				$retval = array();
				$retval["members"] = $this->chat_model->getChatroomMembers( $chatroom_id );
				FNTH_echo_json_response( $retval , 0 , "fo3_exit" );
				break;
			default:
				return parent::handleEvents();
			}
			return parent::handleEvents();
		}
	
		public function __construct( $id , $parent ) {
			parent::__construct( $id , $parent );
			$this->chat_model = new SuperChatModel();
		}

		public function render() {
			if ($this->sRendered) return $this->sRendered;
			$datas = array();
			$datas["chatrooms"]=$this->chat_model->getVisibleChatrooms();
			$datas["last_chat_message_id"]=$this->chat_model->getLastChatMessageId();
			// $datas["last_chat_message_id"]=0;
			FNTHPage::addUniquePageFullInit(sprintf("InitChatPanel('%s',%s);\n",$this->getId(),json_encode($datas)));
			$this->setParam( "datas" , $datas );
			return parent::render();
		}
	}

?>
