import web
from dbadmin import dbadmin
import model
from userdecorators import admin


def get_user(username=""):
    orm = web.ctx.orm
    session = web.ctx.session

    if not username:
        username = session.username

    try:
        query = orm.query(model.User).filter(model.User.name == username).one()
    except:
        query = None
    return query


class Models:
    @admin
    def GET(self):
        return web.ctx.render.user.models()


class ViewModel:
    @admin
    def GET(self, name):
        if name == 'users':
            dbmodel = model.User
        else:
            dbmodel = model.Role

        query = web.ctx.orm.query(dbmodel).all()
        fields = dbmodel.fields()

        return web.ctx.render.dbadmin.listmodel('%s' % name, query, fields,
                BASE_URL='/user/%s' % name, tab='users')


class ItemAdd:
    @admin
    def GET(self, name):
        if name == 'users':
            dbmodel = model.User
        else:
            dbmodel = model.Role
        form = dbadmin.add_form(dbmodel)

        return  web.ctx.render.user.itemedit(form, dbmodel.__name__)

    @admin
    def POST(self, name):
        if name == 'users':
            dbmodel = model.User
        else:
            dbmodel = model.Role
        dbadmin.save_add_form(dbmodel)

        raise web.seeother('/user/%s' % name)


class ItemEdit:
    @admin
    def GET(self, name, itemid):
        if name == 'users':
            dbmodel = model.User
        else:
            dbmodel = model.Role
        item = web.ctx.orm.query(dbmodel).get(itemid)
        form = dbadmin.edit_form(item)
        form.configure(options=[form.password.password()])

        return  web.ctx.render.user.itemedit(form, dbmodel.__name__)

    @admin
    def POST(self, name, itemid):
        if name == 'users':
            dbmodel = model.User
        else:
            dbmodel = model.Role
        item = web.ctx.orm.query(dbmodel).get(itemid)
        prevpass = item.password
        dbadmin.save_edit_form(item)
        # storing password as hash
        if name == 'users':
            pwd = item.password
            if pwd and pwd != prevpass:
                item.set_password(pwd)
            else:
                item.password = prevpass

        raise web.seeother('/user/%s' % name)


class ItemDel:

    @admin
    def GET(self, name, itemid):
        if name == 'users':
            dbmodel = model.User
        else:
            dbmodel = model.Role

        item = web.ctx.orm.query(dbmodel).get(itemid)
        web.ctx.orm.delete(item)

        raise web.seeother('/user/%s' % name)
