## $Id: app.py 12098 2014-11-30 21:00:30Z 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
##
import grok
from zope.authentication.interfaces import IAuthentication
from zope.component import getUtility, getUtilitiesFor
from zope.component.interfaces import ObjectEvent
from zope.pluggableauth import PluggableAuthentication
from waeup.ikoba.authentication import setup_authentication
from waeup.ikoba.datacenter import DataCenter
from waeup.ikoba.mandates.container import MandatesContainer
from waeup.ikoba.interfaces import (
    ICompany, IIkobaPluggable, IObjectUpgradeEvent, IJobManager,
    VIRT_JOBS_CONTAINER_NAME)
from waeup.ikoba.userscontainer import UsersContainer
from waeup.ikoba.utils.logger import Logger
from waeup.ikoba.utils.helpers import attrs_to_fields
from waeup.ikoba.configuration import ConfigurationContainer

from waeup.ikoba.customers.container import CustomersContainer
from waeup.ikoba.products.container import ProductsContainer


class Company(grok.Application, grok.Container, Logger):
    """A company.
    """
    grok.implements(ICompany)

    _curr_doc_id = 101

    _curr_con_id = 101

    # Setup authentication for this app. Note: this is only
    # initialized, when a new instance of this app is created.
    grok.local_utility(
        PluggableAuthentication, provides = IAuthentication,
        setup = setup_authentication,)

    def __init__(self, *args, **kw):
        super(Company, self).__init__(*args, **kw)
        self.setup()
        return

    @property
    def unique_document_id(self):
        """A unique document id for all documents in company.

        The document id returned is guaranteed to be unique. 

        Once a document id was issued, it won't be issued again.

        Obtaining a document id is currently not thread-safe but can be
        made easily by enabling commented lines.
        """
        # lock.acquire() # lock data
        new_id = u'd%s' % (self._curr_doc_id)
        self._curr_doc_id += 1
        # self._p_changed = True
        # commit()
        # lock.release() # end of lock
        return new_id

    @property
    def unique_contract_id(self):
        """A unique contract id for all contract objects in customers.

        The contract id returned is guaranteed to be unique.

        Once a contract id was issued, it won't be issued again.

        Obtaining an contract id is currently not thread-safe but can be
        made easily by enabling commented lines.
        """
        # lock.acquire() # lock data
        new_id = u'c%s' % (self._curr_con_id)
        self._curr_con_id += 1
        # self._p_changed = True
        # commit()
        # lock.release() # end of lock
        return new_id

    def setup(self):
        """Setup some hard-wired components.

        Create local datacenter, containers for users and
        the like.
        """

        self['users'] = UsersContainer()
        self['datacenter'] = DataCenter()
        self['configuration'] = ConfigurationContainer()
        self['mandates'] = MandatesContainer()
        self['customers'] = CustomersContainer()
        self['products'] = ProductsContainer()
        self._createPlugins()

    def _createPlugins(self):
        """Create instances of all plugins defined somewhere.
        """
        for name, plugin in getUtilitiesFor(IIkobaPluggable):
            plugin.setup(self, name, self.logger)
        return

    def traverse(self, name):
        if name == VIRT_JOBS_CONTAINER_NAME:
            return getUtility(IJobManager)
        return None

    def updatePlugins(self):
        """Lookup all plugins and call their `update()` method.
        """
        name = getattr(self, '__name__', '<Unnamed>')
        self.logger.info('Fire upgrade event for site %s' % name)
        grok.notify(ObjectUpgradeEvent(self))
        self.logger.info('Done.')
        self.logger.info('Now upgrading any plugins.')
        for name, plugin in getUtilitiesFor(IIkobaPluggable):
            plugin.update(self, name, self.logger)
        self.logger.info('Plugin update finished.')
        return

attrs_to_fields(Company)


class ObjectUpgradeEvent(ObjectEvent):
    """An event fired, when datacenter storage moves.
    """
    grok.implements(IObjectUpgradeEvent)

@grok.subscribe(Company, grok.IObjectAddedEvent)
def handle_company_added(app, event):
    """If a company is added, a message is logged.
    """
    app.logger.info('Company `%s` added.' % getattr(app, '__name__', None))
    return
