# -*- coding: utf-8 -*-
import logging

from pylons import url, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to
from pylons.i18n import set_lang, get_lang, _, ungettext, N_

from {{package}}.lib.base import BaseController, render, bag_it_and_tag_it

log = logging.getLogger(__name__)

from datetime import datetime
from {{package}} import model as model
from {{package}}.lib.helpers import dcmeta, get_object_or_404
from paste import httpexceptions

from {{package}}.lib.decorators import authorize
from {{package}}.lib.auth.permissions import SignedIn

from tw.api import WidgetBunch
from tw.mods.pylonshf import validate
from {{package}}.forms.identity import *

permission_form = PermissionForm('permission_form', 
                                 location = "headbottom")
new_permission_form = NewPermissionForm('new_permission_form', 
                                        location = "headbottom")

class PermissionsController(BaseController):
    
    def __before__(self):
        c.dcmeta = dcmeta(title="Permission")
    
    @authorize(SignedIn())
    def index(self, **kwargs):
        sq = model.Session.query(model.Permission)
        c.title = c.dcmeta.title = _("Permission Administration")
        c.dc_description = _("Content admin")
        c.permissions = sq.order_by(model.Permission.name.asc())
        return render('dashboard/permissions.mak')
    
    @authorize(SignedIn())
    def show(self, id):
        perm = get_object_or_404(model.Permission, id=id)
        c.dcmeta.title = c.title = c.dcmeta.title + " :: " + perm.name
        c.name = perm.name
        c.content = perm.description + '<br/>Groups: ' + ', '.join(
                    [g.name for g in perm.groups])
        return render('show.mak')
    
    @authorize(SignedIn())
    def new(self):
        """GET /new: Form to create a new item."""
        c.title = "Add permission"
        c.w = WidgetBunch()
        c.w.form = new_permission_form
        c.legend = "Permission ..."
        c.value = None
        c.action = url('create_permission')
        return render('dashboard/permission_add.mak')
    
    @validate(form=new_permission_form, error_handler="new")
    @authorize(SignedIn())
    def create(self):
        permission = model.Permission()
        try:
            # self.form_result.pop('_method')
            for k, v in self.form_result.iteritems():
                setattr(permission, k, v)
            setattr(permission, 'created', datetime.utcnow())
            model.Session.save_or_update(permission)
            model.Session.commit()
            bag_it_and_tag_it(permission, 'permission', u'add')
            model.Session.commit()
            c.flash = "Successful creation"
        except Exception and Exception != httpexceptions.HTTPFound, msg:
            c.flash = "Failed creation"
        session['flash'] = c.flash
        session.save()
        return redirect_to(url('permissions'))
    
    @authorize(SignedIn())
    def edit(self, id):
        """GET /id;edit: Form to edit an existing item."""
        c.permission = get_object_or_404(model.Permission, id=id)
        c.title = _("Editing permission ") + "&#171;%s&#187;" % \
                                                c.permission.name
        c.dc_description = _("Edit permission ") + " %s" % \
                                                c.permission.name
        c.w = WidgetBunch()
        c.w.form = permission_form
        c.legend = "Permission ..."
        c.value = c.permission
        c.action = url('save_permission', id=id)
        return render('dashboard/permission.mak')
    
    @validate(form=permission_form, error_handler="edit")
    @authorize(SignedIn())
    def update(self, id):
        """PUT /id: Update an existing item."""
        c.permission = get_object_or_404(model.Permission, id=id)
        try:
            self.form_result.pop('_method')
            for k, v in self.form_result.iteritems():
                if getattr(c.permission, k) != v:
                    setattr(c.permission, k, v)
            # c.permission = permission
            bag_it_and_tag_it(c.permission, 'permission', u'edit')
            model.Session.commit()
            # Optional -- clear the cache because it'll now be stale
            # cache.get_cache('{{package}}.permission_%s' % \
            #                               c.permission.id).clear()
            c.flash = "Successful update"
        except Exception, msg:
            log.debug('Update: exception detected: %s' % msg)
            c.flash = "Failed update"
        session['flash'] = c.flash
        session.save()
        return redirect_to(url('edit_permission', id=id))
    
    @authorize(SignedIn())
    def delete(self, id):
        """DELETE /id: Delete an existing item."""
        permission = get_object_or_404(model.Permission, id=id)
        try:
            bag_it_and_tag_it(permission, 'permission', u'delete')
            model.Session.delete(permission)
            model.Session.commit()
            session['flash'] = "Successful deletion"
        except Exception, msg:
            session['flash'] = "Failed deletion"
        c.flash = session['flash']
        session.save()
        return redirect_to('permissions')
    
    def popup(self, id):
        c.permission = get_object_or_404(model.Permission, id=id)
        c.title = c.permission.name.decode('utf-8')
        c.content = 'Groups: ' + ', '.join(
                    [g.name for g in c.permission.groups])
        return render('thickbox.mak')
    


