import os
import pyautogui

from flask import Flask
from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for
)
import CMDRConsole.config_parser

keys = config_parser.get_keys()

def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    @app.route('/', methods=('GET', 'POST'))
    def render_general():
        if request.method == 'POST':
            cmd = request.form['btn']
            if not cmd:
                error = 'Key cannot be blank.'
            elif cmd not in keys:
                error = 'Invalid key.'
            else:
                key = keys[cmd]
                pyautogui.press(key)
        return render_template('general.html')
     
    @app.route('/button_press')
    def button_press():
        cmd = request.args.get('btn', 0, type='')
        if not cmd:
            error = 'Key cannot be blank.'
        elif cmd not in keys:
            error = 'Invalid key.'
        else:
            key = keys[cmd]
            pyautogui.press(key)
            
    return app
