import datetime
import sqlite3
from gevent.wsgi import WSGIServer
from flask import Flask, request
app = Flask(__name__)


def create_table():
    conn = sqlite3.connect('name.db')
    conn.execute(
        '''
        CREATE TABLE names
        (
        id INTEGER PRIMARY KEY,
        name CHAR(255),
        created_at DATETIME
        );
        '''
    )

    print("Table tasks created successfully")


def insert_name(name):
    name = str(name)
    if len(name) > 30:
        name = name[0:31]

    name = name.replace(
        "'",
        ' ').replace(
        '"',
        ' ').replace(
            ';',
            ' ').replace(
                '<',
                ' ').replace(
                    '>',
        ' ')

    conn = sqlite3.connect('name.db')
    c = conn.cursor()
    sql = "INSERT INTO names(name, created_at) VALUES('{}', '{}')".format(
        name,
        datetime.datetime.now()
    )

    c.execute(sql)
    conn.commit()

    return name


def get_last_name():
    conn = sqlite3.connect('name.db')
    c = conn.cursor()
    sql = "SELECT name FROM names ORDER BY id DESC LIMIT 1"
    c.execute(sql)
    result = c.fetchone()
    conn.close()

    if result:
        return result[0]

    return 'sunhuachuang'


@app.route("/name", methods=['GET', 'POST'])
def hello():
    if request.method == 'POST':
        return insert_name(request.args['name'])

    return get_last_name()


app.run(port=8000)
# http_server = WSGIServer(('', 8000), app)
# http_server.serve_forever()
