from fogbugz import FogBugz
import sys
from jinja2 import Template
import os
import urllib

def main():

  S_FOGBUGZ_URL   = 'https://mobileretail.fogbugz.com/'
  S_EMAIL         = 'frederik.benoist@gfi.fr'
  S_PASSWORD      = '6brOc-gAr6'
  MAX_BUGS        = 10

  TEMPLATE_FILE = '/Users/fbenoist68/Code/python/fogbugz/fbBackupTemplate.html'

  fb = FogBugz(S_FOGBUGZ_URL)
  fb.logon(S_EMAIL, S_PASSWORD)

  resp = fb.search(q='type:"Cases"',
                   cols='ixBug',
                   max=MAX_BUGS)

  tmpl = Template(open(TEMPLATE_FILE,'r').read())

  for case in resp.cases.findAll('case'):
      ixBug = int(case['ixBug'])
      print(ixBug)

      respBug = fb.search(q='%s' % ixBug,cols ='sTitle,sPersonAssignedTo,sProject,sArea,sCategory,sPriority,events')
      xmlBug = respBug.cases.findAll('case')[0]



      bug = {}
      bug['ixBug'] = int(xmlBug['ixBug'])
      bug['sTitle'] = xmlBug.sTitle.string if xmlBug.sTitle.string else ''
      bug['sPersonAssignedTo'] = xmlBug.sPersonAssignedTo.string if xmlBug.sPersonAssignedTo.string else ''
      bug['sProject'] = xmlBug.sProject.string if xmlBug.sProject.string else ''
      bug['sArea'] = xmlBug.sArea.string if xmlBug.sArea.string else ''
      bug['sCategory'] = xmlBug.sCategory.string if xmlBug.sCategory.string else ''
      bug['sPriority'] = xmlBug.sPriority.string if xmlBug.sPriority.string else ''
      bug['events'] = []

      BACKUP_DIR = '/Users/fbenoist68/Code/python/fogbugz/fogbackup'
      BACKUP_DIR += '/' + xmlBug.sProject.string if xmlBug.sProject.string else ''

      if not os.path.exists(BACKUP_DIR):
        os.makedirs(BACKUP_DIR)

      BACKUP_DIR += '/' + str(xmlBug['ixBug'])

      if not os.path.exists(BACKUP_DIR):
        os.makedirs(BACKUP_DIR)

      for event in xmlBug.events.findAll('event'):
        bugEvent = {}
        bugEvent['ixBugEvent'] = int(event['ixBugEvent'])
        bugEvent['sVerb'] = event.sVerb.string if event.sVerb.string else ''
        bugEvent['dt'] = event.dt.string if event.dt.string else ''
        bugEvent['s'] = event.s.string if event.s.string else ''
        bugEvent['sChanges'] = event.sChanges.string if event.sChanges.string else ''
        bugEvent['evtDescription'] = event.evtDescription.string if event.evtDescription.string else ''
        bugEvent['sPerson'] = event.sPerson.string if event.sPerson.string else ''    
        bugEvent['s'] = event.s.string.encode('ascii', 'ignore').decode('utf-8') if event.s.string else ''
        theAttachments = ''

        for att in event.rgAttachments:
          theAttachments += 'Attachment: ' +att.sFileName.string + '\n'

          print('Downloading attachment: ' + att.sFileName.string)
          str1 = att.sURL.string
          str2 = 'ixAttachment='
          loc1 = str1.find(str2) + len(str2)
          loc2 = str1.find('&amp;sFileName')

          str3 = ';sFileName='
          loc3 = str1.find(str3) + len(str3)
          loc4 = str1.find('&sTicket')

          theURL = S_FOGBUGZ_URL #+ att.sURL.string
          theURL += 'default.asp?'
          theURL += 'ixAttachment=' + str1[loc1:loc2]
          theURL += '&pg=pgDownload&pgType=pgFile&sFilename=' + str1[loc3:loc4]
          theURL += '&token=rnl0t87rp34rfg6q0u0rgbhe85v5r8'

          #fix the replace
          newFileName = att.sFileName.string.replace('/','')
          newFileName = newFileName.replace(':','')
          newFileName = BACKUP_DIR+'/'+newFileName
          print(newFileName)
          urllib.request.urlretrieve(theURL, newFileName)
        bugEvent['attachment'] = theAttachments
        bug['events'].append(bugEvent)




      f = open('%s\\%s.html' % (BACKUP_DIR,bug['ixBug']),'w')
      f.write(tmpl.render(bug=bug))
      f.close()
      fb.view(ixBug=ixBug)


main()

 