"""15th Night Flask App."""

from email_client import send_email, verify_email
from flask import (
    Flask, render_template, redirect, url_for, request, session, flash
)
from flask.ext.login import (
    login_user, current_user, login_required, LoginManager
)
from twilio_client import send_sms
from werkzeug.exceptions import HTTPException

from app import database
from app.database import db_session
from app.forms import RegisterForm, LoginForm, AlertForm, ResponseForm, DeleteUserForm
from app.models import User, Alert, Response
from app.email_client import send_email

try:
    from config import HOST_NAME
except:
    from configdist import HOST_NAME

flaskapp = Flask(__name__)


try:
    flaskapp.config.from_object('config')
except:
    flaskapp.config.from_object('configdist')

flaskapp.secret_key = flaskapp.config['SECRET_KEY']

login_manager = LoginManager()
login_manager.init_app(flaskapp)
login_manager.login_view = 'login'


@login_manager.user_loader
def load_user(id):
    """User loading needed by Flask-Login."""
    return User.query.get(int(id))


@flaskapp.teardown_appcontext
def shutdown_session(response):
    """Database management."""
    database.db_session.remove()

@flaskapp.errorhandler(404)
@flaskapp.errorhandler(Exception)
def error_page(error):
    """Generic Error handling."""
    code = 500
    if isinstance(error, HTTPException):
        code = error.code

    print(error)
    return render_template("error.html", error_code=code), code


@flaskapp.route('/')
def index():
    """Handle routing to the dashboard if logged in or the login page."""
    if current_user.is_authenticated:
        return redirect(url_for('dashboard'))
    return render_template('home.html')

@flaskapp.route('/login', methods=['GET', 'POST'])
def login():
    """Route for handling the login page logic."""
    if current_user.is_authenticated:
        return redirect(url_for('dashboard'))

    # creates instance of form
    form = LoginForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            user = User.get_by_email(request.form['email'].lower())
            passwd = request.form.get("password")
            if user is not None and user.check_password(passwd):
                # session cookie in browser
                session['logged_in'] = True
                login_user(user)
                flash('Logged in successfully.', 'success')
                return redirect(request.args.get('next') or url_for('dashboard'))
            else:
                flash('Invalid Credentials. Please try again.', 'danger')

    return render_template('login.html', form=form)


@flaskapp.route('/dashboard', methods=['GET', 'POST'])