
from flask import Flask, render_template, request, escape
from dbcm import UseDataBase
from vsearch import search4letters
from time import sleep

app = Flask(__name__)
app.config['db_config']={'host': '127.0.0.1',
                         'port': 3306,
                         'use': 'root',
                         'password': '950721',
                         'charset': 'utf8',
                         'database': 'webapps'}


@app.route('/results', methods=['GET', 'POST'])
def do_search() -> 'html':
    phrase = request.form['phrase']
    letters = request.form['letters']
    title = 'Here are your results:'
    results = str(search4letters(phrase, letters))
    try:
        log_sign(request, results)
    except Exception as err:
        print('***logging fails with this: '+ str(err))
    return render_template('results.html',
                           the_title=title,
                           the_phrase=phrase,
                           the_letters=letters,
                           the_results=results,)


@app.route('/')
@app.route('/entry')
def entry_page() -> 'html':
    return render_template('entry.html',
                           the_title='Welcome to webapp on the web!')


@app.route('/viewlog')
def view_log() -> 'html':
    content = []
    with open('flask_log.log') as log:
        for line in log:
            content.append([])
            for item in line.split('|'):
                content[-1].append(escape(item))
    titles = ('Form Data', 'Remote_addr', 'User_agent', 'Results')
    return render_template('viewlog.html', the_title='view log',
                           the_row_titles=titles,
                           the_data=content,)


def log_sign(req: 'flask_request', res: str) -> None:
    # sleep(1500)
    with UseDataBase(app.config['db_config']) as cursor:
        _SQL = """insert into log
                    (phrase, letters, ip, browser_string, results)
                    VALUES 
                    (%s, %s, %s, %s, %s)"""

        cursor.execute(_SQL, (req.form['phrase'],
                              req.form['letters'],
                              req.remote_addr,
                              req.user_agent.browser,
                              res, ))


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