'PDF Representation
-the actual report'

def pdf(self, r, **attr):

    from ..s3.s3codecs.pdf import EdenDocTemplate, S3RL_PDF
    T = current.T
    db = current.db
    s3db = current.s3db
    NONE = current.messages['NONE']
    status_from_activities = current.deployment_settings.get_project_status_from_activities()
    (project, goals) = self._extract(r, **attr)
    record = r.record
    organisation_id = record.organisation_id
    project_id = r.id
    project_title = s3db.project_project_represent(None, record)
    table = s3db.project_project
    date_represent = table.start_date.represent
    ptable = s3db.project_programme
    ltable = s3db.project_programme_project
    query = ((ltable.project_id == project_id) & (ltable.programme_id == ptable.id))
    program = db(query).select(ptable.name, limitby=(0, 1)).first()
    if program:
        program = program.name
    else:
        program = NONE
    stable = s3db.project_status
    status = db((stable.id == record.status_id)).select(stable.name, limitby=(0, 1)).first()
    if status:
        status = status.name
    else:
        status = NONE
    btable = s3db.budget_budget
    budget = db((btable.budget_entity_id == record.budget_entity_id)).select(btable.total_budget, btable.currency, limitby=(0, 1)).first()
    if budget:
        if hasattr(btable.currency, 'represent'):
            currency = btable.currency.represent(budget.currency)
        else:
            currency = budget.currency
        budget = ('%s    %s' % (currency, budget.total_budget))
    else:
        budget = NONE
    htable = s3db.project_hazard
    ltable = s3db.project_hazard_project
    query = ((ltable.project_id == project_id) & (ltable.hazard_id == htable.id))
    hazards = db(query).select(htable.name)
    if hazards:
        hazards = ',    '.join([s3_unicode(T(h.name)) for h in hazards])
    else:
        hazards = NONE
    stable = s3db.org_sector
    ltable = s3db.project_sector_project
    query = ((ltable.project_id == project_id) & (ltable.sector_id == stable.id))
    sectors = db(query).select(stable.name)
    if sectors:
        sectors = ',    '.join([s3_unicode(T(s.name)) for s in sectors])
    else:
        sectors = NONE
    ttable = s3db.project_theme
    ltable = s3db.project_theme_project
    query = ((ltable.project_id == project_id) & (ltable.theme_id == ttable.id))
    themes = db(query).select(ttable.name)
    if themes:
        themes = ',    '.join([s3_unicode(T(t.name)) for t in themes])
    else:
        themes = NONE
    otable = s3db.project_organisation
    query = ((otable.project_id == project_id) & (otable.organisation_id != organisation_id))
    partners = db(query).select(otable.organisation_id, otable.role)
    if partners:
        org_represent = s3db.org_OrganisationRepresent()
        donors = org_represent.bulk([row.organisation_id for row in partners if (row.role == 3)])
        del donors[None]
        donors = donors.values()
        partners = org_represent.bulk([row.organisation_id for row in partners if (row.role != 3)])
        del partners[None]
        partners = partners.values()
    else:
        donors = []
    gtable = s3db.project_location
    query = (gtable.project_id == project_id)
    locations = db(query).select(gtable.location_id)
    if locations:
        location_represent = s3db.gis_LocationRepresent()
        locations = location_represent.bulk([row.location_id for row in locations])
        del locations[None]
        locations = locations.values()
    btable = s3db.project_beneficiary
    query = (btable.project_id == project_id)
    beneficiaries = db(query).select(btable.parameter_id, btable.value)
    if beneficiaries:
        ben_represent = S3Represent(lookup='stats_parameter', translate=True)
        benef_types = ben_represent.bulk(list(set([row.parameter_id for row in beneficiaries])))
        del benef_types[None]
        benefs = []
        sums = {}
        for t in benef_types:
            sums[t] = 0
            for row in beneficiaries:
                if (row.parameter_id == t):
                    sums[t] += row.value
            benefs.append(('%s    %s' % (sums[t], benef_types.get(t))))
        beneficiaries = benefs
    report_title = s3_str(T('Project    Summary    Report'))
    filename = ('%s_%s.pdf' % (report_title, s3_str(project_title)))
    header = DIV(s3db.org_organisation_logo(organisation_id), date_represent(r.utcnow))
    narrative_rows = [TR(TD(T('General    Project    Information')), _colspan=2), TR(TD(T('Project')), TD(record.name)), TR(TD(T('Description')), TD(record.description)), TR(TD(T('Start    Date')), TD(date_represent(record.start_date))), TR(TD(T('End    Date')), TD(date_represent(record.end_date)))]
    nappend = narrative_rows.append
    nappend(TR(TD(T('Locations'), _colspan=2)))
    for l in locations:
        nappend(TR(TD(), TD(l)))
    nappend(TR(TD(T('Donors'), _colspan=2)))
    for d in donors:
        nappend(TR(TD(), TD(d)))
    narrative_rows += (TR(TD(table.human_resource_id.label), TD(table.human_resource_id.represent(record.human_resource_id))), TR(TD(T('Budget')), TD(budget)), TR(TD(T('Hazards')), TD(hazards)), TR(TD(T('Sectors')), TD(sectors)), TR(TD(T('Themes')), TD(themes)))
    nappend(TR(TD(T('Beneficiaries    Reached'), _colspan=2)))
    for b in beneficiaries:
        nappend(TR(TD(), TD(b)))
    nappend(TR(TD(T('Partner    Organizations'), _colspan=2)))
    for p in partners:
        nappend(TR(TD(), TD(p)))
    narrative = TABLE(*narrative_rows)
    if status_from_activities:
        status_table = TABLE(TR(TD(T('Current    Status    of    Project'), _rowspan=2), TD(T('Actual')), TD(T('Planned'))), TR(TD(project_status_represent(project['actual_progress'])), TD(project_status_represent(project['planned_progress']))))
    else:
        status_table = TABLE(TR(TD(T('Current    Status    of    Project'), _rowspan=2), TD(T('Current')), TD(T('Overall'))), TR(TD(project_status_represent(project['current_status'])), TD(project_status_represent(project['overall_status']))))
    sappend = status_table.append
    for goal_id in goals:
        goal = goals[goal_id]
        row = TR(TD(('%s    %s:    %s' % (T('Goal'), goal['code'], goal['name']))), TD(project_status_represent((goal['actual_progress'] if status_from_activities else goal['current_status']))), TD(project_status_represent((goal['planned_progress'] if status_from_activities else goal['overall_status']))), _class='project_goal')
        sappend(row)
        outcomes = goal['outcomes']
        for outcome_id in outcomes:
            outcome = outcomes[outcome_id]
            row = TR(TD(('%s    %s:    %s' % (T('Outcome'), outcome['code'], outcome['name']))), TD(project_status_represent((outcome['actual_progress'] if status_from_activities else outcome['current_status']))), TD(project_status_represent((outcome['planned_progress'] if status_from_activities else outcome['overall_status']))), _class='project_outcome')
            sappend(row)
            outputs = outcome['outputs']
            for output_id in outputs:
                output = outputs[output_id]
                row = TR(TD(('%s    %s:    %s' % (T('Output'), output['code'], output['name']))), TD(project_status_represent((output['actual_progress'] if status_from_activities else output['current_status']))), TD(project_status_represent((output['planned_progress'] if status_from_activities else output['overall_status']))), _class='project_output')
                sappend(row)
                indicators = output['indicators']
                for indicator_id in indicators:
                    indicator = indicators[indicator_id]
                    row = TR(TD(('%s    %s:    %s' % (T('Indicator'), indicator['code'], indicator['name']))), TD(project_status_represent((indicator['actual_progress'] if status_from_activities else indicator['current_status']))), TD(project_status_represent((indicator['planned_progress'] if status_from_activities else indicator['overall_status']))), _class='project_indicator')
                    sappend(row)
                    if status_from_activities:
                        criteria = indicator['criteria']
                        for criteria_id in criteria:
                            criterion = criteria[criteria_id]
                            row = TR(TD(('%s:    %s' % (T('Criterion'), criterion['name']))), TD(project_status_represent(criterion['actual_progress'])), TD(project_status_represent(criterion['planned_progress'])), _class='project_criteria')
                            sappend(row)
                            activities = criterion['activities']
                            for activity_id in activities:
                                activity = activities[activity_id]
                                row = TR(TD(('%s:    %s' % (T('Activity'), activity['name']))), TD(project_status_represent(activity['actual_progress'])), TD(project_status_represent(activity['planned_progress'])), _class='project_activity')
                                sappend(row)
    start_date = project['start_date']
    if start_date:
        start_date = H3(('%s:    %s' % (T('From    Date'), date_represent(start_date))))
    body = DIV(H1(T('Narrative    Report')), start_date, H3(('%s:    %s' % (T('Up    To    Date'), date_represent(project['end_date'])))), narrative, P(''), status_table)
    footer = DIV(('%s:    %s' % (report_title, project_title)))
    doc = EdenDocTemplate(title=report_title)
    printable_width = doc.printable_width
    get_html_flowable = S3RL_PDF().get_html_flowable
    styles = {'tr.project_goal': {'background-color': '#44aaff'}, 'tr.project_outcome': {'background-color': '#ccc1da'}, 'tr.project_output': {'background-color': '#c2d69b'}, 'tr.project_indicator': {'background-color': '#d9d9d9'}}
    header_flowable = get_html_flowable(header, printable_width)
    body_flowable = get_html_flowable(body, printable_width, styles)
    footer_flowable = get_html_flowable(footer, printable_width)
    doc.build(header_flowable, body_flowable, footer_flowable)
    response = current.response
    from gluon.contenttype import contenttype
    response.headers['Content-Type'] = contenttype('.pdf')
    disposition = ('attachment;    filename="%s"' % filename)
    response.headers['Content-disposition'] = disposition
    return doc.output.getvalue()
