<?php

namespace PHPCensor\Model\Build;

/**
 * BitBucket Build Model
 * 
 * @author Dan Cryer <dan@block8.co.uk>
 */
class BitbucketBuild extends RemoteGitBuild
{
    /**
     * Get link to commit from another source (i.e. BitBucket)
     */
    public function getCommitLink()
    {
        return 'https://bitbucket.org/' . $this->getProject()->getReference() . '/commits/' . $this->getCommitId();
    }

    /**
     * Get link to branch from another source (i.e. BitBucket)
     */
    public function getBranchLink()
    {
        return 'https://bitbucket.org/' . $this->getProject()->getReference() . '/src/?at=' . $this->getBranch();
    }

    /**
     * Get the URL to be used to clone this remote repository.
     */
    protected function getCloneUrl()
    {
        $key = trim($this->getProject()->getSshPrivateKey());

        if (!empty($key)) {
            return 'git@bitbucket.org:' . $this->getProject()->getReference() . '.git';
        } else {
            return 'https://bitbucket.org/' . $this->getProject()->getReference() . '.git';
        }
    }

    /**
     * Get a template to use for generating links to files.
     *
     * @return string
     */
    public function getFileLinkTemplate()
    {
        $reference = $this->getProject()->getReference();
        $branch    = $this->getBranch();

        if ($this->getExtra('build_type') == 'pull_request') {
            $matches = [];
            preg_match('/[\/:]([a-zA-Z0-9_\-]+\/[a-zA-Z0-9_\-]+)/', $this->getExtra('remote_url'), $matches);

            $reference = $matches[1];
            $branch    = $this->getExtra('remote_branch');
        }

        $link = 'https://bitbucket.org/' . $reference . '/';
        $link .= 'src/' . $branch . '/';
        $link .= '{FILE}';
        $link .= '#{BASEFILE}-{LINE}';

        return $link;
    }
}
