from mhvdb2.models import Entity, User
from flask import render_template, request, flash, redirect, url_for
from .authentication import authenticate_user, register_user
from flask.ext.login import login_required, current_user, logout_user, current_app
from datetime import datetime, date
from . import admin
from mhvdb2 import resources, app, mailer


def get_post_value(key):
    try:
        return request.form[key]
    except KeyError:
        return None


@admin.route('/')
@login_required
def index():
    return render_template('admin/index.html')


@admin.route("/login", methods=["GET"])
def login():
    # If there are no users, send them to the registration page
    if User.select().count() == 0:
        flash("No admins found, please register the first administrator.", "info")
        return redirect(url_for(".register"))
    return render_template("admin/login.html")


@admin.route("/login", methods=["POST"])
def login_post():
    email = get_post_value("email")
    password = get_post_value("password")
    success = authenticate_user(email, password)
    if success:
        flash("Logged in successfully.", "success")
        next = request.args.get("next", '/')
        return redirect(next)
    else:
        flash("Incorrect email or password.", "danger")
        return render_template("admin/login.html", email=email)


@admin.route("/register", methods=["GET"])
def register():
    # Only allow access if logged in or no users are registered
    if current_user.is_anonymous() and User.select().count() > 0:
        return current_app.login_manager.unauthorized()

    return render_template("admin/register.html")


@admin.route("/register", methods=["POST"])
def register_post():
    # Only allow access if logged in or no users are registered
    if current_user.is_anonymous() and User.select().count() > 0:
        return current_app.login_manager.unauthorized()

    name = get_post_value("name")
    email = get_post_value("email")
    password = get_post_value("password")

    errors = register_user(name, email, password)
    if len(errors) > 0:  # This means that an error has occured
        for e in errors:
            flash(e, 'danger')
        return render_template("admin/register.html", name=name, email=email)
    else:
        flash("User registered successfully.", "success")
        return redirect(url_for('.register'))


@admin.route("/logout", methods=["GET"])
@login_required
def logout():
    logout_user()
    flash("You have been logged out.", "info")
    return redirect(url_for('.index'))


@admin.route('/members')
@login_required
def members():
    members = Entity.select().where(Entity.is_member)
    return render_template('admin/members.html', members=members)


@admin.route('/members/new', methods=['GET'])
@login_required
def member_new():
    return render_template('admin/member.html', new=True)


@admin.route('/members/new', methods=['POST'])
@login_required
def member_new_post():
    name = get_post_value("name")
    email = get_post_value("email")
    phone = get_post_value("phone")
    joined_date = get_post_value("joined_date")
    agreement_date = get_post_value("agreement_date")