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('/')
    def render_general():
        return render_template('general.html')
     
    @app.route('/button_press', methods=['GET','POST'])
    def button_press(cmd = None):
        cmd = request.data.decode("utf-8") 
        if not cmd:
            error = 'Key cannot be blank.'
            print(error)
        elif cmd not in keys:
            error = 'Invalid key.'
            print(error)
        else:
            key = keys[cmd]
            print(key)
            #pyautogui.press(key)
        return "OK"
            
    return app
