<?php

namespace Velis\VersionControl\Svn;

use Velis\Model\DataObject;
use Velis\Model\Cacheable;
use Velis\App;
use Velis\Bpm\Ticket\Ticket;
use User\User;
use Velis\Bpm\Ticket\Log;
use Velis\VersionControl\Svn\Repository\Revision;
use Velis\Model\Routable;

/**
 * Repository model
 *
 * @author Bartosz Izdebski <bartosz.izdebski@velis.pl>
 * @author Olek Procki <olo@velis.pl>
 */
class Repository extends DataObject implements Cacheable, Routable
{
    /**
     * Returns related sql table
     * @return string
     */
    protected function _getTableName()
    {
        return 'app.repository_tab';
    }


    /**
     * Returns revision url
     * @return string
     */
    public function getName()
    {
        return $this->url;
    }


    /**
     * Get short (directory) name of the repository
     */
    public function getShortName()
    {
        return array_pop(explode('/', $this->url));
    }


    /**
     * Import revisions from repository
     * @return void
     */
    public function importRevisions()
    {
        $svn = new Shell($this->url);

        if ($svn->getHeadRevision() <= $this->last_revision_no) {
            return false;
        }

        $revisions    = $svn->getInfo($this->last_revision_no + 1);

        $svnCoding    = array (
            '?\196?\133',
            '?\196?\135',
            '?\196?\153',
            '?\197?\130',
            '?\197?\132',
            '?\195?\179',
            '?\197?\155',
            '?\197?\188',
            '?\197?\186',
            '?\196?\132',
            '?\196?\134',
            '?\196?\152',
            '?\197?\129',
            '?\197?\131',
            '?\195?\147',
            '?\197?\154',
            '?\197?\187',
            '?\197?\185'
        );
        $systemCoding = array ('ą', 'ć', 'ę', 'ł', 'ń', 'ó', 'ś', 'ż', 'ź', 'Ą', 'Ć', '�?', '�?', '�?', 'Ó', 'Ś', 'Ż', 'Ź');

        foreach ($revisions as $revision) {
            $params = array(
                'repository_id'    => $this->repository_id,
                'revision_no'      => $revision['rev'],
                'message'          => $revision['message'] ? str_replace($svnCoding, $systemCoding, $revision['message']) : ' ',
                'repository_login' => $revision['user'],
                'revision_date'    => $revision['date']
            );

            self::$_db->insert('app.repository_revision_tab', $params);

            $repositoryRevId = self::$_db->currval('app.repository_revision_tab_repository_revision_id_seq');

            if (preg_match_all('/(#)([0-9]+)/i', $params['message'], $matches)) {
                $tickets = Ticket::instance($matches[2]);
                foreach ($tickets as $ticket) {
                    $params = array(
                        'repository_revision_id' => $repositoryRevId,
                        'ticket_id' => $ticket->id(),
                        'match_as_resolved' => 0,

                    );
                    self::$_db->insert('app.repository_revision_ticket_tab', $params);
                }
            }

            if (preg_match_all('/(zamyka #)([0-9]+)/i', $params['message'], $matches)) {
                $tickets = Ticket::instance($matches[2]);
                foreach ($tickets as $ticket) {
                    $params = array(
                        'repository_revision_id' => $repositoryRevId,
                        'ticket_id' => $ticket->id(),
                        'match_as_resolved' => 1,

                    );
                    self::$_db->insert('app.repository_revision_ticket_tab', $params);

                    if (!$ticket->isFinished()) {
                        if ($ticket->ticket_status_id != 'Resolved' || $ticket->direction != '<') {
                            if ($user = User::byRepositoryLogin($revision['user'])) {
                                $userId = $user->id();
                            } else {
                                $userId = 1;
                            }

                            $log = Log::factory($ticket);
                            $log['ticket_log_action_id'] = 'Edit';
                            $log['description'] = Lang::get('GENERAL_STATUS_CHANGE_TO') . ' ' . Lang::get('GENERAL_RESOLVED');
                            $log['direction'] = '<';
                            $log['ticket_status_id'] = 'Resolved';
                            $log['user_id'] = $userId;

                            App::$user = User::get($userId);

                            $log->add(true);
                            $log->notify();

                            $ticket->ticket_status_id = 'Resolved';
                            $ticket->direction = '<';
                            $ticket->modify();
                        }
                    }
                }
            }
        }
    }

    /**
     * Returns rewrite route name
     * @return string
     */
    public function getRouteName()
    {
        return 'support-repository';
    }


    /**
     * Returns standard url with no rewrite
     * @return string
     */
    public function getStandardUrl()
    {
        return '/support/repository/index?repository_id=' . $this->id();
    }
}
