from flask import redirect, url_for, send_from_directory
from werkzeug.utils import secure_filename
import os.path
from app import app
from app.models.users import Member
from app.utils import unicode_names
from app.utils.render import render
from config import V5Config


@app.route('/user/<username>')
def user(username):
    norm = unicode_names.normalize(username)
    member = Member.query.filter_by(norm=norm).first_or_404()
    return render('account/user.html', member=member)


@app.route('/user/id/<int:user_id>')
def user_by_id(user_id):
    member = Member.query.filter_by(id=user_id).first_or_404()
    return redirect(url_for('user', username=member.name))

@app.route('/avatar/<filename>')
def avatar(filename):
    filename = secure_filename(filename) # No h4ckers allowed
    if os.path.isfile(V5Config.AVATARS_FOLDER + filename):
        return send_from_directory(V5Config.AVATARS_FOLDER, filename)
    return redirect(url_for('static', filename='images/default_avatar.png'))
