# -*- coding: utf-8 -*-
"""
    xtr
    ~~~~~~
    An atuo-updated personal website powered by
    flask(Python), bootstrap3, sqlite3, webhook.
"""


import os
import urllib2
import mistune
import hmac
import hashlib
from flask import Flask, render_template, request, abort, g, redirect
from sqlite3 import dbapi2 as sqlite3


# Configuration
DEBUG = False
DATABASE = 'xtr.db'
SECRET_KEY = 'development key'
RAW_URL = 'https://raw.githubusercontent.com/MrGba2z/Xtr/master/'
REPO_URL = 'https://github.com/MrGba2z/Xtr/blob/master/'
EMAIL = 'contactxt@icloud.com'
ALLOWED_EXTENSIONS = set(['md', 'markdown', 'mkd'])

# Create application
app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_pyfile('config.py')


def connect_db():
    """Connects to the specific database."""
    rv = sqlite3.connect(app.config['DATABASE'])
    rv.row_factory = sqlite3.Row
    return rv


# Initialize a database
# $sqlite3 xtr.db < schema.sql
def init_db():
    """Initializes the database."""
    db = get_db()
    with app.open_resource('schema.sql', mode='r') as f:
        db.cursor().executescript(f.read())
    db.commit()


def get_db():
    """Opens a new database connection if there is none yet for the
    current application context.
    """
    if not hasattr(g, 'sqlite_db'):
        g.sqlite_db = connect_db()
    return g.sqlite_db


def query_db(query, args=(), one=False):
    cur = get_db().execute(query, args)
    rv = cur.fetchall()
    cur.close()
    return (rv[0] if rv else None) if one else rv


@app.teardown_appcontext
def close_db(error):
    """Closes the database again at the end of the request."""
    if hasattr(g, 'sqlite_db'):
        g.sqlite_db.close()


@app.route('/')