import csv, os
from sqlalchemy.sql.expression import ClauseElement
from models import Session, User

PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
FILENAME = os.path.join(PROJECT_DIR, 'users.csv')

session = Session()

def main():
	import_users()

def import_users():
	with open(FILENAME) as f:
		mycsv = csv.reader(f)
		next(mycsv, None)
		for row in mycsv:
			name = row[0]
			password = row[1]
			user, created = get_or_create(session, User, name=name, password=password)
		session.commit()
		
def get_or_create(session, model, defaults=None, **kwargs):
	instance = session.query(model).filter_by(**kwargs).first()
	if instance:
		return instance, False
	else:
		params = dict((k,v) for k,v in kwargs.iteritems() if not isinstance(v, ClauseElement))
		params.update(defaults or {})
		instance = model(**params)
		session.add(instance)
		return instance, True
 
if __name__ == "__main__":
	main()
