import tg, pylons
from repoze.what.predicates import in_any_group
from webob.exc import HTTPUnauthorized

from bazbase import structure
from bazbase import custom
from bazki import getting

OMNISCIENT_ONLY='This page is restricted to GMs and observers.'
GMS_ONLY='Only GMs can make edits.'
NOT_YOU="You don't have access to this page; try logging in?"
LOG_IN="You must be logged in to access this page."

GROUPS = [u'GM', u'NPC']

# This predicate is used for determining omniscients in custom.
# is_omnisicient() uses this predicate. 
PRED = in_any_group(u'GM', u'NPC',
                    msg=OMNISCIENT_ONLY)
EDITOR_PRED = in_any_group(u'GM', msg=GMS_ONLY)

def is_editor(environ=None):
    if environ is None:
        environ = pylons.request.environ
    return EDITOR_PRED.is_met(environ)

# This is overridden by bazki.custom and gameki.custom to use PRED;
# we can't import directly due to monkeypatching issues.
def is_omniscient(environ=None):
    return custom.is_omniscient(environ)

def logged_in_user():
    if tg.request.identity:
        return tg.request.identity['element']
    else:
        return None
def logged_in_username():
    user = logged_in_user()
    if user:
        return user[u'username'].render()
    else:
        return None

def omniscicent_only():
    tg.flash(OMNISCIENT_ONLY)
    return HTTPUnauthorized()
def not_you():
    tg.flash(NOT_YOU)
    return HTTPUnauthorized()
def log_in():
    tg.flash(LOG_IN)
    return HTTPUnauthorized()

class Restricted(tg.TGController):
    allow_only = PRED

    @tg.expose()
    def _default(self, ename):
        return getting.get(ename, 'html', structure.get_element(ename))

    @tg.expose(template="mako:gameki.templates.casting")
    def casting(self):
        pcs = structure.get_element(pc).get_descendants()
        return {'pcs': pcs}
