# IMPORTS
from flask import Flask, request, redirect, render_template
from flask_sqlalchemy import SQLAlchemy

#---------------------------------------------------------
# FLASK APP AND SQLALCHEMY CONFIGS
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://build-a-blog:04011994@localhost:8889/build-a-blog'
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)

#---------------------------------------------------------
# build-a-blog = DATABASE (DB/db) NAME
# BLOG = TABLE NAME
# ENTRY = SINGLE POST
# POSTS = ALL POSTS IN BLOG
# ID = SINGLE POST'S PRIMARY KEY
# HEADING = ENTRY'S TITLE
# CONTENT = ENTRY'S BODY


#---------------------------------------------------------
# PYTHON PERSISTENT CLASS THAT INITIALLY CREATES TABLE+ROWS IN MYSQL DB
# Bonus Missions:
    # Display the posts in order of most recent to the oldest BY:
        # use the id property that has been created using auto-incrementing
        # OR add a DateTime property to the Blog class (and drop and re-create the table) that will store the date the post was created in the database.

class Blog(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    heading = db.Column(db.String(120))
    content = db.Column(db.String(250))

    def __init__(self,heading,content):
        self.heading = heading
        self.content = content

#---------------------------------------------------------
# APP LOOKS FOR ('/') ON START. MUST REDIRECT

@app.route('/', methods=['GET'])
def start():
    return redirect('/blog')

#---------------------------------------------------------
# TEMPLATE EXTENDS BASE
    # (base.html) DISPLAY NAV LINKS TO:
        # /blog PAGE THAT DISPLAYS POSTS
        # /new_entry PAGE THAT HANDLES THE FORM
# TEMPLATE WILL:
# DISPLAY ALL ENTRIES ON /blog
# DISPLAY ENTRY TITLES AS LINK W/ QUERY URL
# TEMPLATE FOR SPECIFIC ENTRIES
    # designate specific entry displayed by using a query param with the id for that entry in the url.
    # Then handler can get the entry with the id from the db and pass it to the template
    # REVIEW QUERY/PARAMS = Forms in Flask: Accessing Get Request Parameters.
        
        # format that we want the url of a single blog entry to have: 
        # ./blog?id=6 (Here 6 is just one example of an id number for a blog post.) 
        # So using jinja2 templating syntax, how can you make sure that each entry 
        # that is generated on the main page has an href with a query parameter corresponding to its id?

        # The next thing we need to determine is how we are going to 
        # handle an additional GET request on our homepage since we are already handling a GET request there. 
        # Of course, the difference is that in this use case it's a GET request with query parameters. 
        # So we'll want to handle the GET requests differently, returning a different template, 
        # depending on the contents (or lack thereof) of the dictionary request.args.

        # Finally, we need to think about how the template is going to know which blog's data to display. 
        # The blog object will be passed into the template via render_template. 
        # What are the steps we need to take to get the right blog object 
        # (the one that has the id we'll get from the url) from the db and into the render_template function call?

        # create a new database record for the blog entry that has just been submitted, 
        # but before redirecting, you need to grab the id for the record you just created. 
        # That way you'll know what url (i.e., what number to put on the right side of ?id=) 
        # to redirect the user to after they submit their new entry.

        # When you create a new blog post object, it doesn't immediately have an id that is not None. 
        # However, after running db.session.commit(), SQLAlchemy will populate the id property of the object 
        # to be the value auto-generated by the database upon insert. In other words, after you commit, 
        # you can get the id by using the id property of the object you just saved.

@app.route('/blog', methods=['GET'])
def main_page():
    if request.args.get('id'):
        entry_id = request.args.get('id')
        single_entry = Blog.query.get(entry_id)
        return render_template('new_entry.html',tab_title="Blog Home Page",page_header="Most Recent Entry:",single_entry=single_entry)
    
    else:
        posts = Blog.query.all()
        return render_template('blog.html',tab_title="Blog Home Page",page_header="Blogs:",posts=posts)

#---------------------------------------------------------
# TEMPLATE EXTENDS BASE
    # (base.html) DISPLAY NAV LINKS TO:
        # /blog PAGE THAT DISPLAYS ALL ENTRIES
        # /new_entry PAGE THAT HANDLES THE FORM
# DISPLAY THE FORM
# ALLOW USERS TO SUBMIT AN ENTRY
# VALIDATE CRITERIA ON ENTRY SUBMITTED
    # ALL ENTRIES MUST HAVE A TITLE AND BODY
    # TITLE LENGTH + CONTENT LENGTH
# IF ERRORS:
    # RE-RENDER FORM AND ADD:
        # *PREVIOUS USER INPUT
        # ERROR MESSAGES
# AFTER SUMBITTING ENTRY REDIRECT TO DISPLAY ENTRY THROUGH /entry

@app.route('/new_entry', methods=['POST','GET'])
def validate_submit_form():

    if request.method == 'POST':
        heading = request.form['heading']
        content = request.form['content']

        heading_error = ''
        content_error = ''

        if len(heading) > 120:
            heading_error = "Title length requirements: 120 Characters Only"
        if len(heading) == 0:
            heading_error = "Title required to submit."
        if len(content) > 250:
            content_error = "Content length requirements: 250 Characters Only"
        if len(content) == 0:
            content_error = "Content required to submit."
        
        if heading_error or content_error:
            return render_template('form.html',
                tab_title="New Entry",page_header="New Post",
                heading_error=heading_error,content_error=content_error)
        else:
            new_entry = Blog(heading,content)
            db.session.add(new_entry)
            db.session.commit()
            query = "/blog?id=" + str(new_entry.id)
            return redirect(query)
    
    return render_template('form.html',tab_title="New Entry",page_header="New Post")

#---------------------------------------------------------
# "SHIELD THE CODE"
    # Shields any code within the conditional so that the code is only run when this .py file is run directly

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