#!/usr/bin/python
# vim: set fileencoding=utf-8 :
"""
* Copyright (c) 2007 by Paweł Niewiadomski (Atlassian Pty Ltd)
* Copyright (c) 2009 by Tobias Richter (Diamond Light Source Ltd)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in the
*       documentation and/or other materials provided with the distribution.
*     * Neither the name of the names of the contributors nor their 
*       organisations may be used to endorse or promote products derived 
*	from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPY RIGHT HOLDERS ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPY RIGHT HOLDERS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import sys
import re
import time
import commands
import urllib
from trac.env import open_environment
from trac.ticket.model import *
from trac.ticket.query import Query
from trac.web.href import Href
reload(sys)
sys.setdefaultencoding( "utf-8" )
usermap = {
    'randomguy' : 'newname',
}
components=[]
milestones=[]
class DummyHref:
	def ticket(self, id):
		return id
class DummyRef:
	def __init__(self):
		self.href=DummyHref()
def mapUser(user, default=""):
# here you have to specify your own code to map between Trac user and Jira user (maybe it can be transfered intact or using LDAP, AD, etc.)
# ....
    if user == "": 
       return default
    if (user == None): 
       return default
    if user.find("@") > 0:
        user = user[0:user.find("@")]
    if usermap.has_key(user):
        user = usermap[user]    
    return user
def escape(str):
    str = str.replace("&", "&").replace('"', '"').replace("<", "<").replace(">", ">").replace("$", "$").replace("*", "*")
    str = str.replace("{","[").replace("}", "]").replace("[[[", "{noformat}").replace("]]]", "{noformat}").replace("+", "+").replace("", " ").replace("", "\n").replace("", " ")
    return str.encode('iso8859-1', 'xmlcharrefreplace')
def mapIssueType(type):
    type = type.capitalize();
    if type == "Enhancement":
        return "Improvement"
    elif type == "Defect":
        return "Bug"
    elif type == "Task":
        return "Task"
    sys.stderr.write("Fallback to Bug for "+type+"\n")
    return "Bug"
def mapPriority(p):
    #if p == "major" or p == "minor" or p == "normal" or p == "trivial" or p == "critical":
    #return p.capitalize();
    p = p.capitalize();
    if p == "Highest":
        return "Critical"
    if p == "Blocker":
        return "Critical"
    if p == "High":
        return "Major"
    if p == "Critical":
        return "Major"
    if p == "Medium":
        return "Normal"
    if p == "Normal":
        return "Normal"
    if p == "Major":
        return "Normal"
    if p == "Minor":
        return "Minor"
    if p == "Low":
        return "Minor"
    if p == "Trivial":
        return "Trivial"
    if p == "Lowest":
        return "Trivial"
    sys.stderr.write("Fallback to normal priority for "+p+"\n")
    return "Normal"
def mapResolution(r):
    if r == "wontfix":
        return "Won't Fix"
    elif r == "duplicate":
        return "Duplicate"
    elif r == "invalid":
        return "Incomplete"
    elif r == "worksforme":
        return "Cannot Reproduce"
    return "Fixed"
   
summaries = {}
def processTicket(env,id,owner):
    global summaries
    ticket = Ticket(env, id)
    # safeguard against deleted Milestones/Components that still exist in old Tickets
    # these are safe to use even if they exist
    createMilestone(ticket["milestone"])
    createComponent(ticket["component"],"",owner)
    print ''
    state = "open"
    if ticket["status"] == "closed":
        state = "closed"
        print ''
    for ch in ticket.get_changelog():
        if ch[2] == "comment" and ch[4] != "":
            print ''
        elif ch[2] == "resolution":
            if state == "closed":
                print ''
            print ''
            state = "closed"
        elif ch[2] == "attachment":
            try:
                print ''
            except KeyError:
                print ''
def createComponent(name, desc, user):
	if name in components:
		return
	if name != "":
		print ''
		components.append(name)
def createMilestone(name):
	if name in milestones:
		return
	if name != "":
		print ''
		milestones.append(name)
def main():
    sys.stderr.write("Running "+sys.argv[0]+"..\n")
    env = open_environment(sys.argv[1])
    env.projkey=sys.argv[2]
    owner = sys.argv[3]
    ref = DummyRef()
    print ''
    print ''
    print ''
    print '''
 
	'''
    for c in Component(env).select(env):
    	createComponent(c.name,c.description,c.owner)
    for v in Version(env).select(env):
        createMilestone(v.name)
    tickets=[]
    query = Query(env)
    query.max = sys.maxint
    for t in query.execute(ref):
	tickets.append(int(t["id"]))
    tickets.sort()
    for t in tickets:
        processTicket(env, t, owner)
    print ''
    print ''
if __name__ == "__main__":
	main()