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

app = Flask(__name__)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

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

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

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


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


def print_csv_content():
    csv_file_path = os.path.join(BASE_DIR, 'database.csv')
    with open(csv_file_path, newline='') as f:
        reader = csv.reader(f)
        for row in reader:
            print(row)


@app.route('/submit_form', methods=['POST', 'GET'])
def submit_form():
    if request.method == 'POST':
        try:
            data = request.form.to_dict()
            write_to_csv(data)
            return redirect('/thankyou.html')
        except:
            return "did not save to database"
    else:
        return 'Something went wrong. Try again!'


if __name__ == '__main__':
    app.run(debug=True)