# coding=utf-8
from __future__ import absolute_import, unicode_literals, division
from moarcofy.models import Photo, Album, User
from moarcofy.forms import ProfileForm, SettingsForm
from moarcofy import app, config

from hashlib import sha512
from urllib import unquote_plus
from flask import session, request, url_for, flash, redirect, abort


"""Private routes"""


@app.route("/my/", methods=["GET", "POST"])
@app.template("user/home.html")
@app.logged_in
def user_home():
    form = ProfileForm(request.form, session["user"])
    if request.method == "POST" and form.validate():
        user = session["user"]
        user.name = form.name.data
        user.description = form.description.data
        user.save()
        flash("Your profile has been updated!", "success")
        return redirect(url_for("user_home"))

    return {"user": session["user"],
            "form": form}


@app.route("/my/account/", methods=["GET", "POST"])
@app.route("/my/settings/", methods=["GET", "POST"])
@app.template("user/settings.html")
@app.logged_in
def account_settings():
    form = SettingsForm(request.form, session["user"])
    if request.method == "POST" and form.validate():
        user = session["user"]
        user.email = form.email.data
        if form.password.data:
            user.password = sha512("".join([config["salt"]["account"],
                                            form.password.data])).hexdigest()
        user.save()
        flash("Your account has been updated!", "success")
        return redirect(url_for("account_settings"))
    return {"form": form}


"""Public routes"""


@app.route("/user/<id>/")
@app.template("user/view.html")
def public_user(id):
    try:
        user = User.objects.get(id=unquote_plus(id))
    except User.DoesNotExist:
        return abort(404)

    return {"user": user,
            "albums": Album.objects(owner=user).limit(6),
            "photos": Photo.objects(owner=user).limit(12)}
