<?php

namespace Velis\VersionControl\Svn\Repository;

use Velis\Model\DataObject;
use Velis\App;
use Velis\VersionControl\Svn\Repository;

/**
 * Repository revision model
 *
 * @author Bartosz Izdebski <bartosz.izdebski@velis.pl>
 * @author Olek Procki <olo@velis.pl>
 */
class Revision extends DataObject
{

    /**
     * Returns related sql table
     * @return string
     */
    protected function _getTableName()
    {
        return 'app.repository_revision_tab';
    }


    /**
     * Returns datasource for listing function
     * @return string
     */
    protected function _getListDatasource()
    {
        return 'app.repository_revision rr';
    }


    /**
     * Return lastest revision of repository
     *
     * @param int $repositoryId
     * @return int
     */
    public static function getLatestRevision($repositoryId)
    {
        $row = self::$_db->getRow(
            "SELECT MAX(revision_no::numeric) as latest_rev FROM app.repository_revision_tab
             WHERE repository_id = :repository_id",
            array('repository_id' => $repositoryId)
        );

        return intval($row['latest_rev']);
    }


    /**
     * Return the Repository object
     *
     * @return Repository
     */
    public function getRepository()
    {
        return Repository::get($this->repository_id);
    }


    /**
     * Get URL to WebSvn's page for comparing a revision to the previous one
     *
     * @return string
     */
    public function getCompareUrl()
    {
        if (App::$config->phabricator->url) {
            $repository = $this->getRepository();
            $url = App::$config->phabricator->url . '/r';
            $url .=  $repository['acronym'] . $this->revision_no;

            return $url;
        }
    }
}
