import os
import sys
import transaction

from pyramid.paster import (
    get_appsettings,
    setup_logging,
    )

from pyramid.scripts.common import parse_vars

from ..models.meta import Base
from ..models import (
    get_engine,
    get_session_factory,
    get_tm_session,
    )
from ..models.packages import Package, Release


def usage(argv):
    cmd = os.path.basename(argv[0])
    print('usage: %s <config_uri> [var=value]\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]
    options = parse_vars(argv[2:])
    setup_logging(config_uri)
    settings = get_appsettings(config_uri, options=options)

    engine = get_engine(settings)
    Base.metadata.create_all(engine)

    session_factory = get_session_factory(engine)

    with transaction.manager:
        dbsession = get_tm_session(session_factory, transaction.manager)

        p = Package()
        p.id = "Pyramid"
        p.summary = "Micro framework"
        p.author_name = "Chris"
        p.author_email = "chris@gmail.com"
        p.license = 'MIT'

        r1 = Release()
        r1.major_ver = 2
        r1.minor_ver = 0
        r1.build_ver = 4
        r1.size = 105_000

        r2 = Release()
        r2.major_ver = 1
        r2.minor_ver = 0
        r2.build_ver = 3
        r2.size = 100_000
        p.releases.append(r1)
        p.releases.append(r2)

        dbsession.add(p)
