from io import StringIO
from plone import api
from ploneintranet.userprofile.browser.user_import import CSVImportView
from ploneintranet.userprofile.browser.user_import import USER_PORTAL_TYPE

import csv
import re

PATT_NEWLINE = re.compile("(\n|\r)+")


class CSVExportView(CSVImportView):
    def __call__(self):
        portal = api.portal.get()
        workflow_tool = api.portal.get_tool("portal_workflow")
        skip_fields = ["password", "recent_contacts", "portrait"]
        fieldnames = [
            fn for fn in self.available_field_names() if fn not in skip_fields
        ]
        extras = ["review_state"]
        csvstream = StringIO()
        writer = csv.DictWriter(csvstream, fieldnames=(fieldnames + extras))
        writer.writeheader()
        rows = []
        for profile in portal.profiles.objectValues():
            if getattr(profile, "portal_type", "") != USER_PORTAL_TYPE:
                continue
            values = {fn: getattr(profile, fn, "") for fn in fieldnames}
            for key, value in values.items():
                if value and isinstance(value, str):
                    values[key] = PATT_NEWLINE.sub(" ", value)
            values["review_state"] = workflow_tool.getInfoFor(
                ob=profile, name="review_state"
            )
            rows.append(values)
        writer.writerows(rows)
        self.request.response.setHeader("Content-type", "text/csv")
        self.request.response.setHeader(
            "Content-disposition", "inline; filename=quaive_users.csv"
        )
        return csvstream.getvalue()
