#!/usr/bin/python
# -*- encoding: utf-8 -*-

##
## tracaccess.py
## Created on Sat Dec 23 00:10:54 2006
## by Antti Kaihola <antti.kaihola@linux-aktivaattori.org>
## 
## Copyright (C) 2006 Antti Kaihola
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## 
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
## 
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##


import urllib2, cookielib
from itertools import izip, chain


def open_tickets_csv(base_url, report_number, username=None, password=None):
    """
    >>> print open_tickets_csv('http://trac.ambitone.com/ambidjangolib', 3).readline().strip()
    __color__,__group__,ticket,summary,component,version,type,owner,created,_changetime,_description,_reporter
    """
    login_url = '%s/login' % base_url
    report_url = '%s/report/%d?format=csv' % (base_url, report_number)
    if username:
        passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
        passman.add_password(None, base_url, username, password)
        auth_handler = urllib2.HTTPDigestAuthHandler(passman)
        jar = cookielib.CookieJar()
        cookie_processor = urllib2.HTTPCookieProcessor(jar)
        opener = urllib2.build_opener(cookie_processor, auth_handler)
        urllib2.install_opener(opener)
        try:
            urllib2.urlopen(login_url)
            print 'Login page returned no error'
        except urllib2.HTTPError, e:
            print 'Login page returned', e
            if e.code not in (401, 403):
                raise
    return urllib2.urlopen(report_url)


def parse_tickets_csv(site_name, fp):
    """
    >>> p = parse_tickets_csv(iter(('a,b,c\\n', '1,2,3\\n', '4,5,6\\n')))
    >>> p.next() == dict(a='1', b='2', c='3')
    True
    >>> p.next() == dict(a='4', b='5', c='6')
    True
    """
    fields = [field.replace('_', '')
              for field in fp.next().strip().split(',')]
    for row in fp:
        yield dict(chain(izip(fields, row.strip().split(',')),
                         (('site_name', site_name),) ))


def import_tickets_csv(site_name, base_url, report_number, username=None, password=None):
    """
    >>> t = import_tickets_csv('http://trac.ambitone.com/ambidjangolib', 3).next()
    >>> t == dict(__group__=' Release', created='1166805521',
    ...           _changetime='1166805521', component='meta',
    ...           summary='create a logo for ambidjangolib',
    ...           _description='Replace the trac paw logo with something else.',
    ...           version='', _reporter='akaihola', owner='akaihola',
    ...           __color__='5', ticket='4', type='defect')
    True
    """
    return parse_tickets_csv(site_name, open_tickets_csv(base_url, report_number, username, password))


if __name__ == '__main__':
    from doctest import testmod
    testmod()
