<?php

class Notifications extends Model
{
	private static $count = NULL;

	const typePointConfirmed = 'pointConfirmed';
	const typePointDeleted = 'pointDeleted';
	const typeReply = 'reply';
	const typeNewCommentPoint = 'newCommentPoint';
	const typeNewCommentArticle = 'newCommentArticle';
	const typePointLike = 'pointLike';
	const typePointFav = 'pointFav';

	function __construct($fromArray = array())
	{
		$this->_tableName_ = 'notifications';
		parent::__construct($fromArray);
		$this->setRelation('RefUser', 'userId', 'User', 'id', self::TO_ONE);
		$this->setRelation('RefFromUser', 'fromUserId', 'User', 'id', self::TO_ONE);
		$this->setRelation('RefPoint', 'objectId', 'Point', 'id', self::TO_ONE);
		$this->setRelation('RefComment', 'objectId', 'Comment', 'id', self::TO_ONE);
	}

	static function model()
	{
		return new self();
	}

	public static function getUnreadedCount()
	{
		if (!App::$user) {
			return 0;
		}

		if (self::$count === NULL) {
			self::$count = self::model()->getCount(array(
				'where' => '`userId` = '.App::$user->id.' AND `readed` = 0',
			));
		}

		return (int) self::$count;
	}

	public function setAllReaded()
	{
		if (!App::$user) {
			throw new Exception('Попытка пометить все новости прочитанными у неизвестного пользователя.');
		}

		return App::DB()->query('UPDATE `' . $this->_tableName_ . '` SET `readed` = 1 WHERE `userId` = ' . App::$user->id);
	}
}
