# -*- coding: utf8 -*-
import os
import sys
import transaction
import time
import lxml.etree as ET

from sqlalchemy import engine_from_config
from sqlalchemy import create_engine
import unicodedata
import urllib
# Usefull tools
from slugify import slugify
from sqlite3 import dbapi2 as sqlite
from os import path
from pyramid.paster import (
    get_appsettings,
    setup_logging,
    )
from string import printable
from random import choice


from jm2l.models import *
from datetime import datetime

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:
        admin = User(nom=u'jm2l', prenom=u'contact',
            slug=u'contact jm2l', password=u'jm2l',
            mail=u'contact@jm2l.linux-azur.org',
            Staff=1
            )
        DBSession.add(admin)

        # Create 2015 year event
        jm2l = JM2L_Year(year_uid=2015, 
                state="Ongoing",
                description=u"%d, %dème édition des JM2L." % ( 2015, 9 ),
                start_time=datetime.strptime("28-11-2015 10:00","%d-%m-%Y %H:%M"),
                end_time=datetime.strptime("28-11-2015 19:00","%d-%m-%Y %H:%M")
                )
        DBSession.add(jm2l)

        # Create 2015 Physic room event
        phy_salle = SallePhy( name=u"Polytech salle 211",
            description=u"Salle informatique, présence de postes de travail",)
        DBSession.add(phy_salle)
        DBSession.flush()

        # Create matching room place (Name could change each year)
        salle = Salles(name=u"Mystère",  description=u"Salle Mystère",
                    phy_salle_id = phy_salle.uid,
                    year_uid = jm2l.year_uid)
        DBSession.add(salle)

    with transaction.manager:
        # Re-Generate passwords
        for u in DBSession.query(User).filter(User.Staff==None):
            # Fix empty fields
            password = ''.join(choice(printable[:-6]) for _ in range(12))
            u.password = password
            u.Staff = 0
            DBSession.merge(u)
            print u.nom, u.prenom, u.Staff
            