# -*- coding: iso-8859-1 -*-
#
# Copyright (C) 2005 Edgewall Software
# Copyright (C) 2005,2006 Lele Gaifax <lele@metapensiero.it>
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.com/license.html.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://projects.edgewall.com/trac/.
#
# Author: Lele Gaifax <lele@metapensiero.it>

from trac.core import Component, implements
from trac.versioncontrol import IRepositoryConnector
from trac.env import IEnvironmentSetupParticipant
from trac.db import Table, Column, Index, DatabaseManager

from tracdarcs.repos import DarcsRepository
from tracdarcs.cache import DarcsCachedRepository

class DarcsConnector(Component):

    implements(IRepositoryConnector)

    # IRepositoryConnector methods

    def get_supported_types(self):
        """Support the `darcs:` scheme"""
        yield ("darcs", 8)

    def get_repository(self, type, dir, authname):
        """Return a `DarcsRepository`, wrapped by a `DarcsCachedRepository`"""
        db = self.env.get_db_cnx()
        repos = DarcsRepository(db, dir, self.env.log, self.env.config)
        return DarcsCachedRepository(db, repos, None, self.log)

class DarcsSetup(Component):
    """Darcs customizer.

    The darcs backend needs to associate the exact "hash" that identifies
    any single patch to the fake revision number exposed to Trac.
    """

    implements(IEnvironmentSetupParticipant)

    def environment_created(self):
        """After standard environment has been created, add the needed field."""

        db = self.env.get_db_cnx()
        self.upgrade_environment(db)
        db.commit()

    def environment_needs_upgrade(self, db):
        """Check to see if the "hash" field is already there."""

        c = db.cursor()
        try:
            c.execute('SELECT hash FROM revision_hash WHERE rev=1')
            return False
        except:
            return True

    def upgrade_environment(self, db):
        """Actually add the new "hash" field to the revision table."""

        htable = Table('revision_hash', key='rev')[Column('rev'),
                                                   Column('hash',
                                                          type='char(64)'),
                                                   Index(['hash'])]
        connector = DatabaseManager(self.env)._get_connector()[0]
        c = db.cursor()
        for stmt in connector.to_sql(htable):
            c.execute(stmt)
