import Sybase
from albatross import SimpleSessionApp
from albatross.apacheapp import Request


def get_table_list(ctx):
    db = ctx.app.db
    db.execute('use %s' % ctx.locals.database)
    c = db.cursor()
    c.execute('select name from sysobjects'
              ' where type in ("U", "S")'
              ' order by name')
    tables = map(lambda r: r[0], c.fetchall())
    ctx.locals.tables = tables


def get_database_list(ctx):
    c = ctx.app.db.cursor()
    c.execute('select name from master..sysdatabases')
    databases = map(lambda r: r[0], c.fetchall())
    ctx.locals.databases = databases


def get_table_desc(ctx):
    db = ctx.app.db
    db.execute('use %s' % ctx.locals.database)
    c = db.cursor()
    c.execute('select id from sysobjects'
              ' where type in ("U", "S") and name = "%s"' % ctx.locals.table)
    table_id, = c.fetchone()
    c.execute('select c.name, t.name, c.length, c.status'
              ' from syscolumns c, systypes t'
              ' where c.id = %d and c.usertype = t.usertype'
              ' order by c.colid' % table_id)
    ctx.locals.columns = c.fetchall()


def get_table_view(ctx):
    db = ctx.app.db
    db.execute('use %s' % ctx.locals.database)
    c = db.cursor()
    c.execute('select u.name from sysusers u, sysobjects o'
              ' where o.type in ("U","S") and o.name = "%s"'
              ' and o.uid = u.uid' % ctx.locals.table)
    owner, = c.fetchone()
    table = '%s.%s' % (owner, ctx.locals.table)
    c = db.cursor()
    c.execute('select * from %s' % table)
    ctx.locals.desc = c.description
    ctx.locals.rows = c.fetchall()


def request_field(ctx, name):
    if ctx.request.has_field(name):
        return ctx.request.field_value(name)


class TableList:

    name = 'table_list'

    def page_display(self, ctx):
        get_database_list(ctx)
        get_table_list(ctx)
        ctx.run_template('table-list.html')

    def page_process(self, ctx):
        if ctx.req_equals('changedb'):
            ctx.locals.database = request_field(ctx, 'database')
        elif ctx.req_equals('desc'):
            ctx.locals.table = request_field(ctx, 'desc')
            ctx.set_page('table_desc')
        elif ctx.req_equals('view'):
            ctx.locals.table = request_field(ctx, 'view')
            ctx.set_page('table_view')


class TableDesc:

    name = 'table_desc'

    def page_display(self, ctx):
        get_table_desc(ctx)
        ctx.run_template('table-desc.html')

    def page_process(self, ctx):
        if ctx.req_equals('changetable'):
            ctx.locals.table = request_field(ctx, 'table')
        elif ctx.req_equals('back'):
            ctx.set_page('table_list')


class TableView:

    name = 'table_view'

    def page_display(self, ctx):
        get_table_view(ctx)
        ctx.run_template('table-view.html')

    def page_process(self, ctx):
        if ctx.req_equals('changetable'):
            try:
                del ctx.locals.r
            except AttributeError:
                pass
            ctx.locals.table = request_field(ctx, 'table')
        elif ctx.req_equals('back'):
            ctx.set_page('table_list')


class App(SimpleSessionApp):

    def __init__(self):
        SimpleSessionApp.__init__(self,
                                  base_url='sybase.py',
                                  template_path='-=-install_dir-=-',
                                  start_page='table_list',
                                  secret='-=-secret-=-',
                                  session_appid='sybase')
        for page_class in (TableList, TableDesc, TableView):
            self.register_page(page_class.name, page_class())
        self.db = Sybase.connect('rat', 'sa', '')

    def load_session(self, ctx):
        SimpleSessionApp.load_session(self, ctx)
        ctx.default_session_var('database', 'master')
        ctx.default_session_var('tables', [])
        ctx.default_session_var('table', None)

    def create_context(self):
        ctx = SimpleSessionApp.create_context(self)
        ctx.run_template_once('macros.html')
        return ctx


app = App()


def handler(req):
    return app.run(Request(req))
