# import Flask
from flask import Flask, render_template, redirect, request, session, flash
# the "re" module will let us perform some regular expression operations
from mysqlconnection import MySQLConnector
import re
# create a regular expression object that we can use run operations on
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9\.\+_-]+@[a-zA-Z0-9\._-]+\.[a-zA-Z]*$')
app = Flask(__name__)
mysql = MySQLConnector(app,'emaildb')
app.secret_key = "ThisIsSecret!"
@app.route('/', methods=['GET'])
def index():
  return render_template("index.html")

@app.route('/validate', methods=['POST'])
def submit():
    if len(request.form['email']) < 1:
        flash("Email cannot be blank!")
    elif not EMAIL_REGEX.match(request.form['email']):
    	flash("Invalid Email Address!")
    else:
        query = "INSERT INTO emaildb (email, created_at) VALUES (:email, NOW())"
    	# We'll then create a dictionary of data from the POST data received.
    	data = {
             'email': request.form['email'], 
           }
    	mysql.query_db(query, data)
    	return redirect('/success')
    return redirect('/')

@app.route('/success')
def success():
	email = mysql.query_db("SELECT * FROM emaildb")
	print email
	return render_template('success.html', all_email=email)

app.run(debug=True)