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

def create_app(test_config=None):
    global cmds
    global pages
    global page
    global keys
    
    cmds = {} #config_parser.get_cmds()
    pages = config_parser.get_pages()
    keys = config_parser.get_keys()
    page = 'General'
    
    # 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_default():
        return render_template(pages[page])

    @app.route('/General')
    @app.route('/Mining')
    @app.route('/Exploration')
    @app.route('/SRV')
    @app.route('/Assault')
    @app.route('/Keyboard')
    def render_page():
        global page
        rule = request.url_rule
        page = rule.rule.replace('/','');
        return render_template(pages[page])
    
    @app.route('/mouse_move', methods=['POST'])
    def move_mouse():
        d_x = int(request.form['dx'])
        d_y = int(request.form['dy'])
        
        x, y = pyautogui.position()
        new_x = max([x+d_x, 0])
        new_y = max([y+d_y, 0])
        
        try:
            pyautogui.moveTo(new_x, new_y)
        except:
            pass
        
        return "OK"
    
    @app.route('/mouse_tap', methods=['POST'])
    def click_mouse():
        try:
            pyautogui.click()
        except:
            pass
        
        return "OK"
     
    @app.route('/button_press', methods=['GET','POST'])
    def button_press(key = None):
        key = request.data.decode("utf-8") 
        print("'"+key+"'")
        if not key:
            error = 'Key cannot be blank.'
            print(error)
        elif key in cmds:
            cmd = cmds[key]
            pyautogui.press(cmd)
        elif key in keys:
            cmd = keys[key]
            pyautogui.press(cmd)
        else:
            try:
                pyautogui.press(key)
            except:
                pass
        return "OK"
            
    return app
