from flask import Flask, render_template, url_for, request, redirect
import csv

app = Flask(__name__)


@app.route('/')
def my_home():
    return render_template('index.html')


@app.route('/<string:page_name>')
def html_page(page_name):
    return render_template(page_name)


# def write_to_file(data):
#     with open(file='database.txt', mode='a') as database:
#         email = data["email"]
#         subject = data["subject"]
#         message = data["message"]
#         database.txt = database.write(f'\n{email},{subject},{message}')


def write_to_csv(data):
    with open('database.csv', mode='a', newline='') as database:
        email = data["email"]
        subject = data["subject"]
        message = data["message"]
        csv_writer = csv.writer(database, delimiter=',',
                                quotechar='"', quoting=csv.QUOTE_MINIMAL)
        csv_writer.writerow([email, subject, message])


# The Request Object
# POST: browser wants us to save information. GET: browser wants us to send information.
@app.route('/submit_form', methods=['POST', 'GET'])
def submit_form():
    if request.method == 'POST':
        try:
            data = request.form.to_dict()
            # print(data)
            # write_to_file(data)
            write_to_csv(data)
            # return 'Form Submitted!'
            return redirect('/thankyou.html')
        except:
            return 'Did not save to database.'
    else:
        return 'Something went wrong. Try again!'


# --------------------Terminal-------------------------
# set FLASK_APP=server.py
# flask run
# out put: Running on http://127.0.0.1:5000/
# Debug Mode: On --> set FLASK_ENV=development


# --------------------git clone-------------------------
# git config --global user.name "Soulian-Li"
# git config --global user.email liang.li1104@gmail.com

# other commands
# git clone (url)
# git add (file names)
# git commit -m "(committed message)
# git push -u origin master
# git remote add origin master (url)
