## $Id: userscontainer.py 9198 2012-09-18 21:04:39Z henrik $
##
## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
## 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
##
"""Users container for the Kofa portal.
"""
import grok
from zope.event import notify
from waeup.kofa.authentication import Account
from waeup.kofa.interfaces import IUsersContainer
from waeup.kofa.utils.logger import Logger
from waeup.kofa.utils.batching import ExporterBase
from waeup.kofa.interfaces import ICSVExporter
from waeup.kofa.interfaces import MessageFactory as _


class UsersContainer(grok.Container, Logger):
    """A container for principals.

    See interfaces.py and users.txt for extensive description.
    """
    grok.implements(IUsersContainer)
    grok.require('waeup.manageUsers')

    def addUser(self, name, password, title=None,
                description=None, email=None, phone=None,
                public_name= None, roles=[]):
        """Add a new Account instance, created from parameters.
        """
        if title is None:
            title = name
        #if description is None:
        #    description = title
        self[name] = Account(name=name, password=password, title=title,
                             description=description, public_name=public_name,
                             email=email, phone=phone, roles=roles)
        #self.logger.info('User account %s added.' % name)

    def addAccount(self, account):
        """Add the account passed.
        """
        self[account.name] = account
        #self.logger.info('User account %s added.' % account.name)

    def delUser(self, name):
        """Delete user, if an account with the given name exists.

        Do not complain, if the name does not exist.
        """
        if name in self.keys():
            del self[name]
            #self.logger.info('User account %s deleted.' % name)


class UsersExporter(grok.GlobalUtility, ExporterBase):
    """Exporter for user accounts.
    """
    grok.implements(ICSVExporter)
    grok.name('users')

    #: Fieldnames considered by this exporter
    fields = ('name', 'title', 'public_name', 'description',
              'email', 'phone', 'roles', 'local_roles', 'password')

    #: The title under which this exporter will be displayed
    title = _(u'Users')

    def mangle_value(self, value, name, context=None):
        """Treat location values special.
        """

        if name == 'local_roles' and context is not None:
            local_roles = context.getLocalRoles()
            value = {}
            for role in local_roles.keys():
                objects = local_roles[role]
                object_list = []
                for object in objects:
                    object.__class__.__name__
                    object_list.append((object.__name__, object.__class__.__name__))
                value[role] = object_list
        return super(
            UsersExporter, self).mangle_value(
            value, name, context=context)

    def export(self, users, filepath=None):
        """Export `users`, an iterable, as CSV file.

        If `filepath` is ``None``, a raw string with CSV data is returned.
        """
        writer, outfile = self.get_csv_writer(filepath)
        for user in users:
            self.write_item(user, writer)
        return self.close_outfile(filepath, outfile)

    def export_all(self, site, filepath=None):
        """Export users into filepath as CSV data.

        If `filepath` is ``None``, a raw string with CSV data is returned.
        """
        users = site.get('users', {})
        return self.export(users.values(), filepath)
