# w.c.s. - web application for online forms
# Copyright (C) 2005-2010  Entr'ouvert
#
# 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, see <http://www.gnu.org/licenses/>.

from quixote.directory import Directory, AccessControlled
from quixote import get_publisher, get_request, get_response

from .. import _
from .. import errors

class BackofficeRootDirectory(AccessControlled, Directory):

    @classmethod
    def register_directory(cls, urlname, directory):
        setattr(cls, urlname, directory)

    @classmethod
    def register_menu_item(cls, url, title, **options):
        for i, v in enumerate(cls.menu_items):
            if v[0] == url:
                del cls.menu_items[i]
        if title is None:
            # used to remove an item
            return
        cls.menu_items.append((url, title, options))

    def _q_access(self):
        get_response().breadcrumb.append( ('backoffice/', _('Back Office')) )

        user = get_request().user
        if not user and get_publisher().user_class.count() > 0:
            raise errors.AccessUnauthorizedError(
                    public_msg = _('Access to backoffice is restricted to authorized persons only. '\
                                   'Please login.'))
        if user and not user.can_go_in_backoffice():
            raise errors.AccessForbiddenError()

        get_response().filter['in_backoffice'] = True

    def get_menu_items(self):
        return self.menu_items
