# -*- coding: utf-8 -*-
# Copyright (c) 2012 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
"""
    web.blueprints.user
    ~~~~~~~~~~~~~~

    This module defines view functions for /user

    :copyright: (c) 2012 by AG DSN.
"""

from flask import Blueprint, render_template, flash, redirect, url_for
from pycroft.model import user, session
from pycroft.model.user import User
from web.blueprints import BlueprintNavigation
from web.blueprints.user.forms import UserSearchForm, UserCreateForm
from pycroft.model import dormitory
import datetime

bp = Blueprint('user', __name__, )
nav = BlueprintNavigation(bp, "Nutzer")


def sort_key(dormitory):
    key = 0
    power = 1
    for char in reversed(dormitory.number.lower()):
        key += ord(char) * pow(10, power)
        power += power

    return key


@bp.route('/')
@nav.navigate(u"Übersicht")
def overview():
    dormitories_list = dormitory.Dormitory.q.all()
    dormitories_list = sorted(dormitories_list,
        key=lambda dormitory: sort_key(dormitory))

    return render_template('user/overview.html',
        dormitories=dormitories_list)

@bp.route('/show/<user_id>')
def user_show(user_id):
    user_list = user.User.q.filter(User.id == user_id).all()
    return render_template('user/user_show.html',
        page_title=u"Nutzer anzeigen: " + user_id,
        user=user_list)

@bp.route('/dormitory/<dormitory_id>')
def dormitory_floors(dormitory_id):
    floors_list = ["dummy 1", "dummy 2", "dummy 3"]
    return render_template('user/floors.html',
        floors=floors_list, page_title=u"Etagen Wohnheim XY")

@bp.route('/create', methods=['GET', 'POST'])
@nav.navigate("Anlegen")
def create():
    form = UserCreateForm()
    if form.validate_on_submit():
        myUser = user.User(login=form.login.data,
            name=form.name.data, room_id=form.room_id.data, registration_date=datetime.datetime.now())
        session.session.add(myUser)
        session.session.commit()
        flash('Benutzer angelegt', 'success')
        return redirect(url_for('.overview'))
    return render_template('user/user_create.html',
        page_title=u"Neuer Nutzer", form=form)


@bp.route('/search', methods=['GET', 'POST'])
@nav.navigate("Suchen")
def search():
    form = UserSearchForm()
    if form.validate_on_submit():
        # Check: with_entities
        #userResult = user.User.q.with_entities()
        userResult = user.User.q
        if len(form.userid.data):
            userResult = userResult.filter(User.id == form.userid.data)
        if len(form.name.data):
            userResult = userResult.filter(User.name.like('%' + form.name\
            .data + '%'))
        if len(form.login.data):
            userResult = userResult.filter(User.login == form.login.data)
	if len(userResult.all()) == 0:
	    flash('Benutzer nicht gefunden', 'error')
        return render_template('user/user_search.html', page_title=u"Suchergebnis",
                               results=userResult.all(), form=form)
    return render_template('user/user_search.html', form=form)

@@ -678,17 +678,25 @@
 datetime
+, random
 %0A
-
 %0Abp = Bl
@@ -1241,32 +1241,33 @@
 mitories_list)%0A%0A
+%0A
 @bp.route('/show
@@ -1490,16 +1490,17 @@
 _list)%0A%0A
+%0A
 @bp.rout
@@ -1728,16 +1728,311 @@
 m XY%22)%0A%0A
+%0Adef generate_Password():%0A    ZEICHEN = %22abcdefghijklmnopqrstuvwxyz!$%25&()=.,:;-_#+1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ%22%0A    PASSWORD_LENGTH = 8%0A    password = %22%22%0A    for i in range(PASSWORD_LENGTH):%0A        password = password + ZEICHEN%5Brandom.choice(range(len(ZEICHEN)))%5D%0A    return password%0A%0A%0A
 @bp.rout
@@ -2279,16 +2279,28 @@
 id.data,
+%0A           
  registr
@@ -3203,17 +3203,24 @@
 n.data)%0A
-%09
+        
 if len(u
@@ -3246,9 +3246,16 @@
  0:%0A
-%09
+        
     
@@ -3351,16 +3351,28 @@
 h.html',
+%0A           
  page_ti
@@ -3392,35 +3392,16 @@
 ebnis%22,%0A
-                   
         

add a function generate_Password()