#####################################################################
#
# updater       Update existing JTracker instances
#
# This software is governed by a license. See
# LICENSE.txt for the terms of this license.
#
#####################################################################
__version__='$Revision: 1.7 $'[11:-2]

from copy import deepcopy
from string import zfill

def update(self, REQUEST):
    """ Update existing instances """
    jtrackers = self.objectValues(['JTracker'])
    if len(jtrackers) == 0:
        return 'No JTracker found!'

    log = []

    for jt in jtrackers:

        # Fix up misnaming of first issue
        faulty_first_issue = jt._getOb('issues_1', None)
        if faulty_first_issue:
            faulty_first_issue.unindexObject()
            jt._delObject('issues_1')

            faulty_first_issue._setId('issue_1')
            faulty_first_issue.id = 'issue_1'
            jt._setObject('issue_1', faulty_first_issue)
            first_object = jt._getOb('issue_1')
            first_object.indexObject()

            log.append('- Fixed mis-named first issue')

        # Updates from version 1.1 to 1.2
        if not jt.hasProperty('mailhost'):
            cur_props = list(jt._properties)
            cur_props.append( { 'id' : 'mailhost'
                              , 'type' : 'string'
                              , 'mode' : 'w'
                              } )
            jt._properties = tuple(cur_props)

            log.append('- Set missing "mailhost" property')

        if not getattr(jt, 'mailhost', ''):
            mh = getattr(jt, 'MailHost')
            mh_path = '/%s' % mh.absolute_url(1)
            jt.mailhost = mh_path


        if not jt.hasProperty('filesize_limit'):
            cur_props = list(jt._properties)
            cur_props.append( { 'id' : 'filesize_limit'
                              , 'type' : 'int'
                              , 'mode' : 'w'
                              } )
            jt._properties = tuple(cur_props)

            log.append('- Set missing "filesize_limit" property')

        if not getattr(jt, 'filesize_limit', ''):
            jt.filesize_limit = 0

        # Updates from version 1.3 to 1.4
        if not jt.hasProperty('accept_email'):
            cur_props = list(jt._properties)
            cur_props.append( { 'id' : 'accept_email'
                              , 'type' : 'boolean'
                              , 'mode' : 'w'
                              } )
            jt._properties = tuple(cur_props)

            log.append('- Set missing "accept_email" property')

        if not getattr(jt, 'accept_email', ''):
            jt.accept_email = 0

        # Updates from version 1.2 to 1.3
        jt_admin = jt.getProperty('admin_email')
        jt_admin_str = '"JTracker Admin" <%s>' % jt_admin
        log.append('- Fixing issue subscriber lists')
        jt_cat = jt.catalog

        if jt_cat.Indexes._getOb('issue_number', None) is not None:
            jt_cat.delIndex('issue_number')

        for issue in list(jt.objectValues(['JTracker Issue'])):
            poster_email = issue.getProperty('requester_email')
            poster_name = issue.getProperty('requester_name')
            poster_str = '"%s" <%s>' % (poster_name, poster_email)

            have_poster = 0
            have_admin = 0

            subscribers = filter(None, issue.getProperty('subscribers'))
            for subscriber in subscribers:
                if subscriber.find(poster_email) != -1:
                    have_poster = 1

                if subscriber.find(jt_admin) != -1:
                    have_admin = 1

            if not have_poster:
                subscribers.append(poster_str)
                log.append('   - Added requester to subscribers (%s)' % issue.getId())

            if not have_admin:
                subscribers.append(jt_admin_str)
                log.append('   - Added admin to subscribers (%s)' % issue.getId())

            issue._updateProperty('subscribers', subscribers)

            old_id = issue.getId()
            old_id_num = old_id.split('_')[1]

            if len(old_id_num) < 5:
                new_id_num = zfill(old_id_num, 5)
                new_id = 'issue_%s' % new_id_num

                if jt._getOb(new_id, None) is None:
                    issue.unindexObject()
                    jt._delObject(old_id)

                    issue.id = new_id
                    issue._setId(new_id)
                    jt._setObject(new_id, issue)

                    new_issue = jt._getOb(new_id)
                    url = '/'.join(new_issue.getPhysicalPath())
                    jt_cat.catalog_object(new_issue, url)

                    log.append('   - Updated id %s to id %s' % (old_id, new_id))

        # Updates from 1.6 to 1.7
        if not jt.hasProperty('admin_name'):
            cur_props = list(jt._properties)
            cur_props.append( { 'id' : 'admin_name'
                              , 'type' : 'string'
                              , 'mode' : 'w'
                              } )
            jt._properties = tuple(cur_props)

            log.append('- Set missing "admin_name" property')

        if not getattr(jt, 'admin_name', ''):
            jt.admin_name = 'JTracker Admin'

    log.append('\nDone!')

    REQUEST.RESPONSE.setHeader('Content-type', 'text/plain')
    return '\n'.join(log)



def BTreeConverter(self, REQUEST):
    """ convert an existing JTracker to a BTree-based JTracker """
    try:
        from Products import BTreeFolder2
    except ImportError:
        return 'BTreeFolder2 product is not installed!'

    jtrackers = self.objectValues(['JTracker'])
    if len(jtrackers) == 0:
        return 'No JTracker found!'

    log = []

    for jt in jtrackers:
        log.append('- Found JTracker at /%s' % jt.absolute_url(1))

        if hasattr(jt, '_tree'):
            log.append('- ALREADY BTREE_BASED')
            continue
        
        jt_id = jt.getId()
        mh = getattr(jt, 'mailhost', None)
        if mh is None:
            mh = '/%s' % getattr(jt, 'MailHost').absolute_url(1)
        objects = jt.objectValues()
        self._delObject(jt_id)

        constructor = self.manage_addProduct['JTracker'].manage_addJTracker
        apply( constructor
             , ( jt_id, )
             , { 'title' : getattr(jt, 'title')
               , 'description' : getattr(jt, 'description')
               , 'abbreviation' : getattr(jt, 'abbreviation')
               , 'admin_account' : getattr(jt, 'admin_account')
               , 'admin_email' : getattr(jt, 'admin_email')
               , 'jtracker_emailname' : getattr(jt, 'jtracker_emailname')
               , 'jtracker_emailaddress' : getattr(jt, 'jtracker_emailaddress')
               , 'mailhost' : mh
               }
             )
        log.append('- Created new JTracker')
        new_jt = getattr(self, jt_id)
        new_jt.components = getattr(jt, 'components')
        new_jt.request_types = getattr(jt, 'request_types')
        new_jt._accounts = deepcopy(jt._accounts)
        cat = getattr(new_jt, 'catalog')
        
        log.append('- Transferring issues')
        for ob in objects:
            ob_id = ob.getId()
            if ob_id != 'catalog':
                log.append('   - %s' % ob_id)
                new_jt._setObject(ob_id, ob)

                new_issue = new_jt._getOb(ob_id)
                url = '/'.join(new_issue.getPhysicalPath())
                cat.catalog_object(new_issue, url)

        log.append('- Finished\n\n')

    log.append('Done!')

    REQUEST.RESPONSE.setHeader('Content-type', 'text/plain')

    return '\n'.join(log)
