'Import Incident Reports from Ushahidi
@ToDo: Deployment setting for Ushahidi instance URL'

@staticmethod
def irs_ushahidi_import(r, **attr):

    T = current.T
    auth = current.auth
    request = current.request
    response = current.response
    session = current.session
    system_roles = session.s3.system_roles
    ADMIN = system_roles.ADMIN
    if (not auth.s3_has_role(ADMIN)):
        auth.permission.fail()
    if ((r.representation == 'html') and (r.name == 'ireport') and (not r.component) and (not r.id)):
        url = r.get_vars.get('url', 'http://')
        title = T('Import    Incident    Reports    from    Ushahidi')
        form = FORM(TABLE(TR(TH(B(('%s:    ' % T('URL')))), INPUT(_type='text', _name='url', _size='100', _value=url, requires=[IS_URL(), IS_NOT_EMPTY()]), TH(DIV(SPAN('*', _class='req', _style='padding-right:    5px;')))), TR(TD(B(('%s:    ' % T('Ignore    Errors?')))), TD(INPUT(_type='checkbox', _name='ignore_errors', _id='ignore_errors'))), TR('', INPUT(_type='submit', _value=T('Import')))))
        rheader = DIV(P(('%s:    http://wiki.ushahidi.com/doku.php?id=ushahidi_api' % T('API    is    documented    here'))), P(('%s    URL:    http://ushahidi.my.domain/api?task=incidents&by=all&resp=xml&limit=1000' % T('Example'))))
        output = dict(title=title, form=form, rheader=rheader)
        if form.accepts(request.vars, session):
            import_count = [0]
            def count_items(job, import_count=import_count):
                if (job.tablename == 'irs_ireport'):
                    import_count[0] += 1
            current.s3db.configure('irs_report', deduplicate=count_items)
            vars = form.vars
            ushahidi_url = vars.url
            import os
            stylesheet = os.path.join(request.folder, 'static', 'formats', 'ushahidi', 'import.xsl')
            if (os.path.exists(stylesheet) and ushahidi_url):
                ignore_errors = vars.get('ignore_errors', None)
                try:
                    success = r.resource.import_xml(ushahidi_url, stylesheet=stylesheet, ignore_errors=ignore_errors)
                except:
                    import sys
                    e = sys.exc_info()[1]
                    response.error = e
                else:
                    if success:
                        count = import_count[0]
                        if count:
                            response.confirmation = ('%s    %s' % (import_count[0], T('reports    successfully    imported.')))
                        else:
                            response.information = T('No    reports    available.')
                    else:
                        response.error = self.error
        response.view = 'create.html'
        return output
    else:
        raise HTTP(405, current.ERROR.BAD_METHOD)
