<?php

require_once('util.php');
require_once('media.php');

class pb_Comment {
    protected $id;
    protected $repositoryId = 0;
    protected $mediaId = 0;
    protected $content = NULL;
    protected $date = NULL;
    protected $userId = 0;

    public function __construct($repositoryId, $mediaId, $content, $date, $userId) {
        $this->repositoryId = $repositoryId;
        $this->mediaId = $mediaId;
        $this->content = $content;
        $this->date = $date;
        $this->userId = $userId;
    }
    public function getId() {
        return $this->id;
    }
    public function setId($id) {
        $this->id = $id;
    }
    public function getRepositoryId() {
        return $this->repositoryId;
    }
    public function setRepositoryId($repositoryId) {
        $this->repositoryId = $repositoryId;
    }
	public function getMediaId() {
        return $this->mediaId;
    }
	public function setMediaId($mediaId) {
        $this->mediaId = $mediaId;
    }
	public function getContent() {
        return $this->content;
    }
	public function setContent($content) {
        $this->content = $content;
    }
	public function getDate() {
        return $this->date;
    }
	public function setDate($date) {
        $this->date = $date;
    }
	public function getUserId() {
        return $this->userId;
    }
	public function setUserId($userId) {
        $this->userId = $userId;
    }
	public function insert() {
        // consider a transaction
        $connection = Helper::getInstance()->getSQL();
        $connection->executef("INSERT INTO " . DB_PREFIX . "COMMENT (REPOSITORY_ID, MEDIA_ID, CONTENT, DATE, USER_ID)"
            . " VALUES(%d, %d, '%s', FROM_UNIXTIME(%d), %d)",
            $this->repositoryId, $this->mediaId, $this->content, $this->date, $this->userId);
        if ($connection->getUpdateCount() != 1) {
            throw new Exception("Database failure");
        }
        $this->setId($connection->lastInsertId());
    }
    public function update() {
        if ($this->id == NULL) {
            throw new Exception('Invalid id');
        }
        $connection = Helper::getInstance()->getSQL();
        $connection->executef('UPDATE ' . DB_PREFIX . 'COMMENT SET CONTENT=\'%s\', DATE=' .
            sql_Connection::fromTimestamp('%d') . ' WHERE ID=%d', $this->content, $this->date, $this->id);
        if ($connection->getUpdateCount() != 1) {
            throw new Exception('Database failure');
        }
    }
    public function delete() {
        if ($this->id == NULL) {
            throw new Exception('Invalid id');
        }
        $connection = Helper::getInstance()->getSQL();
        $connection->executef('DELETE FROM ' . DB_PREFIX . 'COMMENT WHERE ID=%d', $this->id);
        if ($connection->getUpdateCount() != 1) {
            throw new Exception('Database failure');
        }
        pb_Media::removeComment($this->mediaId);
    }
    public static function fetchFromId($id) {
        $connection = Helper::getInstance()->getSQL();
        $connection->executef('SELECT ' . pb_Comment::getSelectionFields() . ' FROM ' . DB_PREFIX . 'COMMENT WHERE ID=%d', $id);
        $rs = $connection->getResultSet();
        if (! $rs->next()) {
            return NULL;
        }
        return pb_Comment::createFromResultSet($rs);
    }
    public static function deleteByMediaId($mediaId) {
        $connection = Helper::getInstance()->getSQL();
        $connection->executef('DELETE FROM ' . DB_PREFIX . 'COMMENT WHERE MEDIA_ID=%d', $mediaId);
        return $connection->getUpdateCount();
    }
    public static function createFromResultSet($rs) {
        $object = $rs->getRowObject();
        $comment = new pb_Comment($object->REPOSITORY_ID, $object->MEDIA_ID, $object->CONTENT, $object->DATE, $object->USER_ID);
        $comment->setId($object->ID);
        return $comment;
    }
    public static function getSelectionFields() {
        return 'ID, REPOSITORY_ID, MEDIA_ID, CONTENT, ' . sql_Connection::toTimestamp('DATE') . ', USER_ID';
    }
    public static function initializeTable() {
        $connection = Helper::getInstance()->getSQL();
        $connection->execute('DROP TABLE IF EXISTS ' . DB_PREFIX . 'COMMENT');
        $connection->execute('CREATE TABLE ' . DB_PREFIX . 'COMMENT (' .
            'ID bigint(20) unsigned NOT NULL auto_increment,' .
            'MEDIA_ID bigint(20) unsigned NOT NULL,' .
            'REPOSITORY_ID bigint(20) unsigned NOT NULL,' .
            'CONTENT text NOT NULL default \'\', ' .
            'DATE datetime NOT NULL default \'0000-00-00 00:00:00\', ' .
            'USER_ID bigint(20) unsigned NOT NULL,' .
            'PRIMARY KEY (ID)' .
            ') CHARACTER SET utf8 COLLATE utf8_bin');
    }
}

function comment_add($exchange) {
    $request = $exchange->getRequest();
    $mediaId = $request->getAttribute('mediaId');
    $content = $request->getAttribute('content');
    $authUser = $exchange->getServer()->getContextKey('user');
    $media = pb_Media::fetchFromId($mediaId);
    if ($media == NULL) {
        throw new Exception("Media id " . $mediaId . " not found");
    }
    $comment = new pb_Comment($media->getRepositoryId(), $mediaId, $content, time(), $authUser->getId());
    // TODO transaction
    $comment->insert();
    pb_Media::addComment($comment->getMediaId());
    $exchange->done("Comment inserted");
}

function comment_modify($exchange) {
    $request = $exchange->getRequest();
    $id = $request->getAttribute('id');
    $content = $request->getAttribute('content');
    $authUser = $exchange->getServer()->getContextKey('user');
    $comment = pb_Comment::fetchFromId($id);
    if ($comment == NULL) {
        throw new Exception("Comment id " . $id . " not found");
    }
    if ($comment->getUserId() != $authUser->getId()) {
        throw new Exception('Not owner');
    }
    $comment->setContent($content);
    $comment->setDate(time());
    $comment->update();
    $exchange->done("Comment Modified");
}

function comment_delete($exchange) {
    $request = $exchange->getRequest();
    $id = $request->getAttribute('id');
    $authUser = $exchange->getServer()->getContextKey('user');
    $comment = pb_Comment::fetchFromId($id);
    if ($comment == NULL) {
        throw new Exception("Comment id " . $id . " not found");
    }
    if (($comment->getUserId() != $authUser->getId()) && (! $authUser->hasRight('admin'))) {
        throw new Exception('Not owner');
    }
    $comment->delete();
    $exchange->done("Comment deleted");
}

function comment_list($exchange) {
    $request = $exchange->getRequest();
    $mediaId = $request->getAttribute('mediaId');
    $connection = Helper::getInstance()->getSQL();
    $connection->executef('SELECT ' . pb_Comment::getSelectionFields() . ' FROM ' . DB_PREFIX .
        'COMMENT WHERE MEDIA_ID = %d', $mediaId);
    $response = $exchange->createResponseElement('commentListResult');
    $rs = $connection->getResultSet();
    while ($rs->next()) {
        $comment = pb_Comment::createFromResultSet($rs);
        $response->appendChild($exchange->createResponseElement('comment', array(
            'id' => $comment->getId(),
            'repositoryId' => $comment->getRepositoryId(),
            'mediaId' => $comment->getMediaId(),
            'content' => $comment->getContent(),
            'date' => $comment->getDate(),
            'userId' => $comment->getUserId()
        )));
    }
    $exchange->replyXML($response);
}

function comment_listMedias($exchange) {
    $request = $exchange->getRequest();
    $from = sxe_Server::getDOMElementAttribute($request, 'from', 0);
    $limit = sxe_Server::getDOMElementAttribute($request, 'limit', 100);
    $connection = Helper::getInstance()->getSQL();
    $authUser = $exchange->getServer()->getContextKey('user');
    $repositoryIds = pb_Repository::getRepositoryIdsByUserId($authUser->getId());
    $response = $exchange->createResponseElement('commentListResult');
    foreach ($repositoryIds as $repositoryId) {
        if ($limit <= 0) {
            break;
        }
        $connection->executef('SELECT MEDIA_ID, ' . sql_Connection::toTimestamp('MAX(DATE)', 'MAX_DATE') . ' FROM ' . DB_PREFIX .
            'COMMENT WHERE REPOSITORY_ID = %d AND DATE >= ' . sql_Connection::fromTimestamp('%d') .
            ' GROUP BY MEDIA_ID ORDER BY DATE DESC LIMIT %d', $repositoryId, $from, $limit);
        $rs = $connection->getResultSet();
        while ($rs->next()) {
            $comment = $rs->getRowObject();
            $response->appendChild($exchange->createResponseElement('comment', array(
                'mediaId' => $comment->MEDIA_ID,
                'lastDate' => $comment->MAX_DATE
            )));
            $limit--;
        }
    }
    $exchange->replyXML($response);
}

?>