<?php 
class MessageApi extends Api{
	
	private function __formatMessageList($message) {
		foreach ($message as $k => $v) {
			$message[$k] = $this->__formatMessageDetail($v);
		}
		return $message;
	}
	
	private function __formatMessageDetail($message) {
		unset($message['deleted_by']);
		$message['from_uname']	= getUserName($message['from_uid']);
		$message['to_uname']	= getUserName($message['to_uid']);
		$message['from_face']	= getUserFace($message['from_uid']);
		$message['to_face']		= getUserFace($message['to_uid']);
		$message['timestmap']	= $message['ctime'];
		$message['ctime']		= date('Y-m-d H:i', $message['ctime']);
		return $message;
	}
	
	// 返回用户的最新n条私信，并包含发送者和接受者的ID,姓名,头像
	public function inbox() {
		$this->data['type'] 	= $this->data['type']	? $this->data['type'] : 'all';
		$this->data['order']	= $this->data['order'] == 'ASC'	? 'message_id ASC' : 'message_id DESC';
		$message = model('Message')->getInboxByUidFromApi($this->mid, $this->data['type'], $this->since_id, $this->max_id, $this->count, $this->page, $this->data['order']);
		$message = $this->__formatMessageList($message);
		return $message;
	}
	
	// 获取当前用户发送的最新私信列表
	public function outbox() {
		$this->data['order'] = $this->data['order'] == 'ASC'	? 'message_id ASC' : 'message_id DESC';
		$message = model('Message')->getOutboxByUidFromApi($this->mid, $this->since_id, $this->max_id, $this->count, $this->page, $this->data['order']);
		$message = $this->__formatMessageList($message);
		return $message;
	}
	
	// 获取当前登陆用户的私信详情
	public function show() {
		$show_cascade = ($this->data['show_cascade'] !== '0');
		$res = model('Message')->getDetailById($this->mid, $this->data['id'], $show_cascade);
		if ($show_cascade) {
			return $this->__formatMessageList($res);
		}else {
			return empty($res) ? $res : $this->__formatMessageDetail($res);
		}
	}
	
	// 发送私信
	public function create() {
		if ( empty($this->data['to_uid']) || empty($this->data['title']) || empty($this->data['content']) ) {
			return false;
		}
		$data['to'] 		= $this->data['to_uid'];
		$data['title']		= $this->data['title'];
		$data['content']	= $this->data['content'];
		return model('Message')->postMessage($data, $this->mid);
	}
	
	// 回复私信
	public function reply() {
		if ( empty($this->data['id']) || empty($this->data['content']) ) {
			return false;
		}
		return model('Message')->replyMessage($this->data['id'], $this->data['content'], $this->mid);
	}
	
	// 删除私信
	public function destroy() {
		return model('Message')->deleteMessageById($this->mid, t($this->data['message_id']));
	}
}

?>