import os

from quixote import get_publisher, redirect
from quixote.directory import Directory
from quixote.html import TemplateIO, htmltext

from wcs.qommon import _
from wcs.qommon.publisher import get_publisher_class

import wcs.backoffice.management
import wcs.root
from wcs.categories import Category
from wcs.formdef import FormDef

from wcs.qommon import get_cfg, errors
from wcs.qommon.form import *

CURRENT_USER = object()

def check_visibility(target, user=CURRENT_USER):
    if not get_publisher().has_site_option('auquotidien-%s' % target):
        # option not explicitely enabled, -> off.
        return False
    if user is CURRENT_USER:
        user = get_request().user
    if not user:
        return False
    target = target.strip('/')
    if target == 'management':
        target = 'forms'
    if target == 'strongbox':
        if not get_publisher().has_site_option(target):
            # strongbox disabled in site-options.cfg
            return False
        if not get_cfg('misc', {}).get('aq-strongbox'):
            # strongbox disabled in settings panel
            return False
    admin_role = get_cfg('aq-permissions', {}).get(target, None)
    if not admin_role:
        return False
    if not (user.is_admin or admin_role in (user.roles or [])):
        return False
    return True


class BackofficeRootDirectory(wcs.backoffice.root.RootDirectory):
    def get_intro_text(self):
        return _('Welcome on Publik back office interface')

    def _q_index(self):
        if len(self.get_menu_items()) == 1:
            return redirect(self.get_menu_items()[0]['url'])
        return wcs.backoffice.root.RootDirectory._q_index(self)

    def home(self):
        return redirect('management/')

get_publisher_class().backoffice_directory_class = BackofficeRootDirectory
