##############################################################################
#
# convertTracker    convert a Tracker to a JTracker
#
# This software is governed by a license. See
# LICENSE.txt for the terms of this license.
# 
##############################################################################

from DateTime.DateTime import DateTime
from Products.JTracker.JTracker import manage_addJTracker
from Products.JTracker.JTrackerIssue import manage_addJTrackerIssue

REPLY_TYPE_MAP = { 'note' : 'Comment'
                 , 'correspond' : 'Comment'
                 , 'accepted' : 'Accept'
                 , 'resolved' : 'Resolve'
                 , 'reframed' : 'Comment'
                 , 'rejected' : 'Reject'
                 , 'deferred' : 'Defer'
                 , 'diverted' : 'Comment'
                 }

def convert(self, REQUEST):
    trackers = self.objectValues('Tracker')

    if not trackers:
        return 'No Tracker Found!'

    for tracker in trackers:
        jtracker_id = 'j%s' % tracker.getId()
        if jtracker_id in self.objectIds():
            self._delObject(jtracker_id)
        desc = getattr(tracker, 'description', '')
        desc.replace('\n', '')
        comps = filter(None, getattr(tracker, 'component_range', []))
        rts = filter(None, getattr(tracker, 'type_range', []))
        loc_roles = tracker.get_local_roles()
        admin_name = ''
        for user_id, roles in loc_roles:
            if 'TrackerOwner' in roles:
                admin_name = user_id

        manage_addJTracker( self
                          , jtracker_id
                          , getattr(tracker, 'title', '')
                          , desc.strip()
                          , getattr(tracker, 'abbrev', '')
                          , admin_name
                          , getattr(tracker, 'adminaddr', '')
                          , ''
                          , ''
                          )

        jtracker = getattr(self, jtracker_id)

        jtracker.manage_changeProperties( REQUEST=None
                                        , components=comps
                                        , request_types=rts
                                        )

        issue_keys = map(lambda x: x, tracker._issues.keys())
        issue_keys.sort()

        for key in issue_keys:
            issue = tracker._issues.get(key)

            if issue is None:
                continue

            no_mail = 'unknown@dataflake.org'
            no_name = 'Anonymous Coward'

            old_date = getattr(issue, 'date', DateTime())
            new_date = DateTime(old_date.timeTime()).toZone('US/Eastern')
            email_dict = getattr(issue, 'alt_emails', {}) or {}
            name_dict = getattr(issue, 'alt_full_names', {}) or {}
            requester = getattr(issue, 'requester', '')
            requester_email = email_dict.get(requester, no_mail) or no_mail
            requester_name = name_dict.get(requester, no_name) or no_name
            tv = getattr(issue, 'traitVals', [])
            request_type = 'unknown'
            component = 'unknown'
            for key, val in tv:
                if key == 'type':
                    request_type = val
                elif key == 'component':
                    component = val

            id = manage_addJTrackerIssue( jtracker
                                        , getattr(issue, 'title', '')
                                        , getattr(issue, 'description', 'n/a') or 'n/a'
                                        , component
                                        , request_type
                                        , requester_name
                                        , requester_email
                                        , []
                                        )

            new_issue = getattr(jtracker, id)

            replies = issue._messages
            reply_keys = map(lambda x: x, replies.keys())
            reply_keys.sort()
            ##now = DateTime()

            for reply_key in reply_keys:
                reply = replies.get(reply_key)

                if reply is None:
                    continue

                reply_date = getattr(reply, 'date', None)
                if not isinstance(reply_date, DateTime):
                    if getattr(reply, 'id') == '1':
                        reply_date = DateTime(old_date.timeTime()).toZone('US/Eastern')
                    else:
                        reply_date = DateTime(previous_date.timeTime())

                previous_date = reply_date

                rn = getattr(reply, 'from', '')
                if rn == 'jens': rn = 'Jens Vagelpohl'
                if rn == 'Anonymous User' or rn == 'Anonymous': rn = no_name
                re = getattr(reply, 'alt_email', '')
                if rn == 'Jens Vagelpohl': re = 'jens@dataflake.org'

                if getattr(reply, 'id') == '1':
                    fns = getattr(issue, 'alt_full_names', {}) or {}
                    if rn != no_name and requester_name == no_name:
                        new_issue.requester_name = rn

                    if getattr(reply, 'id', '') == '1':
                        if rn == no_name and requester_name != no_name:
                            rn = requester_name

                if getattr(reply, 'msgrole', '') == 'request':
                    # Initial request
                    if rn and new_issue.requester_name != rn:
                        new_issue._updateProperty('requester_name', rn)

                    if not rn and new_issue.requester_name:
                        rn = new_issue.requester_name

                    if re and new_issue.requester_email != re:
                        new_issue._updateProperty('requester_email', re)

                    if not re and new_issue.requester_email:
                        re = new_issue.requester_email

                    first_reply = new_issue._replies['entry_1']
                    if first_reply['requester_email'] == no_mail:
                        first_reply['requester_email'] = re

                    first_reply['reply_date'] = new_date

                else:
                    msgrole = getattr(reply, 'msgrole', 'note')
                    try:
                        reply_type = REPLY_TYPE_MAP[msgrole]
                    except:
                        import traceback; traceback.print_exc()
                    new_issue.addReply( reply_type
                                      , getattr(reply, 'description', 'n/a') or 'n/a'
                                      , rn or no_name
                                      , re or no_mail
                                      , 0
                                      , reply_date
                                      )

            stage_val = getattr(issue, 'stage', 'Pending')
            new_issue.manage_changeProperties( REQUEST=None
                                             , stage=stage_val.capitalize()
                                             )
            new_issue._updateProperty('request_date', new_date)

            new_issue.indexObject()


    return 'OK'

