__author__ = 'tanshu'

from zope.sqlalchemy import ZopeTransactionExtension
from sqlalchemy.ext.declarative import declarative_base
import transaction
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension(), expire_on_commit=False))
Base = declarative_base()


def initialize_sql(engine):
    from .auth import Permission, Role, User, role_group, user_role
    from .master import Tax, Modifier, ProductGroup, FoodTable, DbSetting
    from .voucher import RunningTable

    DBSession.configure(bind=engine)
    Base.metadata.bind = engine
    Base.metadata.create_all(engine)
    #fixtures()


def fixtures():
    import uuid
    from .auth import Permission, Role, User, role_group, user_role
    from .master import Tax, Modifier, ProductGroup, FoodTable
    from .voucher import RunningTable

    user = User('Admin', '123456', False, id=uuid.UUID('8de98592-76d9-c74d-bb3f-d6184d388b5a'))
    DBSession.add(user)
    permissions = [Permission('Users', uuid.UUID('c5b7d9d7-f178-0e45-8ea4-bf4e08ec901b')),
                   Permission('Taxes', uuid.UUID('c830872a-ba1b-4593-800e-dd0573eea930')),
                   Permission('Product Groups', uuid.UUID('08413a22-cf88-fd43-b2b7-365d2951d99f')),
                   Permission('Products', uuid.UUID('74fa6d21-eebb-e14c-8153-bebc57190ab4')),
                   Permission('Food Tables', uuid.UUID('f31a8e97-9ee0-4dbb-9016-637c03fbb646')),
                   Permission('Modifiers', uuid.UUID('0e88b9f8-3ed6-4304-b3cf-5a66c96ac650'))]
    owner = Role('Owner', uuid.UUID('52e08c0c-048a-784f-be10-6e129ad4b5d4'))
    DBSession.add(owner)
    for permission in permissions:
        DBSession.add(permission)
        owner.permissions.append(permission)
    user.roles.append(owner)
    tax = Tax('Tax Free', 0, '08c3101d-cdab-449f-9574-a025c8ae5556', True)
    modifiers = [Modifier('Spicy', True, uuid.UUID('d1b76d14-ab02-45c8-8a37-3197113e7bd5')),
                 Modifier('Mild', True, uuid.UUID('c49ed960-6635-4347-8b30-41258f372894')),
                 Modifier('Less Oily', True, uuid.UUID('972593ee-2196-4978-a4b2-e91e9e5cac5d'))]
    for modifier in modifiers:
        DBSession.add(modifier)
    pgrs = [ProductGroup('Beer', 1, 'Beer', 0, True),
            ProductGroup('Whisky', 1, 'Alcohol', 0, True),
            ProductGroup('Wine', 1, 'Alcohol', 0, True),
            ProductGroup('Main Course', 1, 'Food', 0, True),
            ProductGroup('Appetizers', 1, 'Food', 0, True)]
    for pgr in pgrs:
        DBSession.add(pgr)

    for i in range(1,20):
        DBSession.add(FoodTable('Table No ' + str(i),'Test Location'))
    DBSession.add(tax)
    transaction.commit()