# -*- coding: utf-8 -*-

from flask import Flask, session, redirect, url_for, escape, request, render_template, flash, abort
from dataManager import PostManager, UserManager
from artical import artical, from_json
from json import JSONDecoder
import json
import user
import functools

app = Flask(__name__)
app.secret_key = 'fAf2k3fjSA@#dfs'

def login_required(fn):
    @functools.wraps(fn)
    def inner(*args, **kwargs):
        if session.get('logged_in'):
            return fn(*args, **kwargs)
        return redirect(url_for('login', next=request.path))
    return inner

@app.route("/", methods=['GET', 'POST'])
def index():
    articals = PostManager().getArticalsByPage(1)
    return render_template('index.html', articals = articals) 

@app.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        if UserManager().login(username, password):
            session['logged_in'] = True
            session['username'] = username
            session.permanent = True  # Use cookie to store session.
            return redirect(url_for('index'))
        else:
            flash('Incorrect password.', 'danger')
            return render_template('login.html', username = username, password = password)
    if session.get('logged_in'):
        return redirect(url_for('index'))
    return render_template('login.html')

@app.route('/edit/', methods=['GET', 'POST'])
@login_required
def create_artical():
    if request.method == 'POST':
        title = request.form['artical_title'] 
        content = request.form['artical_content'] 
        slug = request.form['artical_slug'] 
        keywords = request.form['artical_keywords'] 
        newArtical = artical(title = title, content = content, slug = slug, keywords = keywords)
        PostManager().insertPost(newArtical)
        return redirect(url_for('index'))
    return render_template('edit_artical.html')

@app.route('/edit/<identifier>', methods=['GET', 'POST'])
@login_required
def edit_artical(identifier):
    if request.method == 'POST':
        title = request.form['artical_title'] 
        content = request.form['artical_content'] 
        slug = request.form['artical_slug'] 
        keywords = request.form['artical_keywords'] 
        new_artical = artical(identifier = identifier, title = title, content = content, slug = slug, keywords = keywords)
        PostManager().update_artical(new_artical) 
        return redirect(url_for('index'))
    else:
        origin_artical = PostManager().getArticalByID(identifier)
        return render_template('edit_artical.html', artical = origin_artical)

@app.route('/delete/<identifier>', methods=['GET'])
@login_required
def delete_artical(identifier):
    PostManager().delete_artical(identifier)
    return redirect(url_for('index'))


@app.route('/blog/id/<identifier>', methods=['GET'])
def showPostByID(identifier):
    artical = PostManager().getArticalByID(identifier)
    if not artical:
        abort(404)
    return render_template('blog.html', artical = artical)


@app.route('/blog/<slug>/', methods=['GET'])
def showPost(slug):
    artical = PostManager().getArticalBySlug(slug)
    if not artical:
        abort(404)
    return render_template('blog.html', artical = artical)
    
@app.route('/preview/', methods=['POST'])
def preview():
    title = request.form['artical_title'] 
    content = request.form['artical_content'] 
    slug = request.form['artical_slug'] 
    keywords = request.form['artical_keywords'] 
    newartical = artical(title = title, content = content, slug = slug, keywords = keywords, published = False)
    return render_template('blog.html', artical = newartical)

@app.route('/logout/', methods=['GET'])
def logout():
    session.clear()
    return redirect(url_for('index'))

 
if __name__ == "__main__":
    app.debug = True
    app.run(host = '0.0.0.0', port = 9090)


