import os
import sys
import transaction

from sqlalchemy import engine_from_config

from pyramid.paster import (
    get_appsettings,
    setup_logging,
    )

from .models import (
    DBSession,
    Config,
    Device_type,
    Device,
    Doc,
    Tag,
    Tag_val,
    Card,
    GaugeOffVal,
    WellTest,
    Note,
    EventConfig,
    Event,
    RunStatus,
    FluidShot,
    BackupRestore,
    Base,
    )


def usage(argv):
    cmd = os.path.basename(argv[0])
    print('usage: %s <config_uri>\n'
          '(example: "%s development.ini")' % (cmd, cmd))
    sys.exit(1)


def main(argv=sys.argv):
    if len(argv) != 2:
        usage(argv)
    config_uri = argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.create_all(engine)
    with transaction.manager:
        # Device Type Seeds
        device_type_CLX = Device_type(device_type='CLX')
        device_type_u800 = Device_type(device_type='Micro800')
        device_type_E300 = Device_type(device_type='E300')

        DBSession.add(device_type_CLX)
        DBSession.add(device_type_u800)
        DBSession.add(device_type_E300)

        # Device Seeds
        main_plc = Device(device_type_id=1, address="192.168.1.10")
        DBSession.add(main_plc)
