from flask import Flask, render_template, request, redirect, url_for, send_file
import toml
import os

from PIL import Image, ImageDraw, ImageFont, ImageOps
import re
import time
import widgets.widget as widget
import argparse

app = Flask(__name__)

mydir = os.path.dirname(os.path.abspath(__file__))
# print(mydir)
###mydir = os.path.join(mydir, '../')
# print(mydir)

def convert(input):
    if isinstance(input, dict):
        return dict((convert(key), convert(value)) for key, value in input.iteritems())
    elif isinstance(input, list):
        return [convert(element) for element in input]
    elif isinstance(input, unicode):
        return input.encode('utf-8')
    else:
        return input

####################################################
####################################################
####################################################

uni_config = toml.load(os.path.join(mydir, 'config.toml'))
config = convert(uni_config)

config2 = {'resWidth': 640,  'resHeight': 384, 'cellsWidth': 3, 'cellsHeight': 3, 'widgets': [
{'type': 'image', 'posX': 0, 'posY': 0, 'width': 3, 'height': 3, 'bwStyle': 'mono', 'scaleMode': 'fill', 'filename': 'forest.jpg'},
{'type': 'trello', 'posX': 0, 'posY': 0, 'width': 1, 'height': 3, 'board': 'Organisation', 'list': 'Plans'},
{'type': 'trello', 'posX': 1, 'posY': 0, 'width': 2, 'height': 3, 'board': 'E-paper', 'list': 'To Do:'}
]}

cwidth = int(round(int(config['resWidth'])/int(config['cellsWidth'])))
cheight = int(round(int(config['resHeight'])/int(config['cellsHeight'])))

image_yellow = Image.new('1', (config['resWidth'], config['resHeight']), 255)    # 255: clear the frame
draw_yellow = ImageDraw.Draw(image_yellow)
image_black = Image.new('1', (config['resWidth'], config['resHeight']), 255)    # 255: clear the frame
draw_black = ImageDraw.Draw(image_black)

####################################################
####################################################
####################################################

# HOMEPAGE
@app.route('/home', methods=['GET', 'POST'])
def home(): # Toml config passed to html page via two dicts.
            # Form data passed back to webserver as JSON.
    config = read_config()
    widgLists, sysList = prep_dict_for_web(config)

    if request.method == 'POST':
        jsonData = request.get_json()
        print(jsonData)
        jsonData = convert(jsonData)

        # update system variables
        for key in sysList:
            print("%" + jsonData[key] + "$")
            if jsonData[key]:
                if isInt(jsonData[key]):
                    #print(request.form[key] + " is int")
                    sysList[key] = int(jsonData[key])
                else:
                    sysList[key] = jsonData[key]
        # update widget variables
        # for i in range(len(widgLists)):
        #   for key in widgLists[i]:
        #       if request.form[key+str(i)]:
        #           widgLists[i][key] = request.form[key+str(i)]
        for i in range(len(widgLists)):
            for key in widgLists[i]:
                # print(request.form[key+str(i)])
                if jsonData[key + str(i)]:
                    if isInt(jsonData[key + str(i)]):
                        #print(request.form[key+str(i)] + " is int")
                        widgLists[i][key] = int(jsonData[key + str(i)])
                    else:
                        widgLists[i][key] = jsonData[key + str(i)]

        update_config(widgLists, sysList)

    widgTypes = widgetTypes()

    return render_template('home.html', title='Overview', widgLists=widgLists, sysList=sysList, widgTypes=widgTypes)

@app.route('/newWidget', methods=['GET', 'POST'])
def newWidget(): #
    #if request.method == 'GET':
    widgType = request.args['type']
    conf_defaults = pull_default_conf(widgType)
    #import pdb; pdb.set_trace()
    if request.method == 'POST':
        #widgType = request.form['ty']
        jsonData = request.get_json()
        print(jsonData)
        jsonData = convert(jsonData)

    return render_template('newWidget.html', title='Overview', conf_defaults=conf_defaults)


@app.route('/display', methods=['GET', 'POST'])
def display(): 
    location = 'test/imgBlack.bmp'
    updateWidgets()
    return send_file(location)


def pull_default_conf(widgType=None):
    uni_config = toml.load(os.path.join(mydir, 'config.toml'))
    config = convert(uni_config)

    conf_dict = {
        'trello': {
            'board': {'default': '', 'datatype': 'text'},
            'list': {'default': '', 'datatype': 'text'},
            'width': {'default': 1, 'datatype': 'number', 'min': 1, 'max': config['cellsWidth']},
            'height': {'default': 1, 'datatype': 'number', 'min': 1, 'max': config['cellsHeight']},
            'posX': {'default': 0, 'datatype': 'number', 'min': 0, 'max': config['cellsWidth']-1},
            'posY': {'default': 0, 'datatype': 'number', 'min': 0, 'max': config['cellsHeight']-1}
        },
        'text': {
            'text': {'default': 'abcdefghijklmnopqrstuvwxyz', 'datatype': 'text'},
            'width': {'default': 1, 'datatype': 'number', 'min': 1, 'max': config['cellsWidth']},
            'height': {'default': 1, 'datatype': 'number', 'min': 1, 'max': config['cellsHeight']},
            'posX': {'default': 0, 'datatype': 'number', 'min': 0, 'max': config['cellsWidth']-1},
            'posY': {'default': 0, 'datatype': 'number', 'min': 0, 'max': config['cellsHeight']-1}
        },
        'image': {
            'file': {'default': 'img.jpg', 'datatype': 'text'},
            'bwMode': {'default': 'mono', 'datatype': 'text'},
            'scaleMode': {'default': 'fill', 'datatype': 'text'},
            'width': {'default': 1, 'datatype': 'number', 'min': 1, 'max': config['cellsWidth']},
            'height': {'default': 1, 'datatype': 'number', 'min': 1, 'max': config['cellsHeight']},
            'posX': {'default': 0, 'datatype': 'number', 'min': 0, 'max': config['cellsWidth']-1},
            'posY': {'default': 0, 'datatype': 'number', 'min': 0, 'max': config['cellsHeight']-1}
        }
    }

    if widgType != None:
        conf_dict = conf_dict.get(widgType)

    return conf_dict

def widgetTypes():
    dflt_conf = pull_default_conf()
    widgTypes = []
    for key in dflt_conf.keys():
        widgTypes.append(key)
    return widgTypes

def isInt(s):
    try:
        int(s)
        return True
    except ValueError:
        return False


def prep_dict_for_web(config):
    widgLists = config['widgets']  # list of dicts
    sysList = {}  # dict
    for key in config:
        if key != 'widgets':
            sysList[key] = config[key]
    return widgLists, sysList


def read_config():
    uni_config = toml.load(os.path.join(mydir, 'config.toml'))
    config = convert(uni_config)
    # print(config)
    # config = {'widgets': [
    #{'width': 3, 'posX': 0, 'posY': 0, 'scaleMode': 'fill', 'bwStyle': 'mono', 'type': 'image', 'filename': 'forest.jpg', 'height': 3},
    #{'list': 'Plans', 'height': 3, 'width': 1, 'board': 'Organisation', 'posX': 0, 'posY': 0, 'type': 'trello'},
    #{'list': 'To Do:', 'height': 3, 'width': 2, 'board': 'E-paper', 'posX': 1, 'posY': 0, 'type': 'trello'}
    # ], 'cellsHeight': 3, 'resHeight': 384, 'resWidth': 640, 'cellsWidth': 3}
    return config


def update_config(widgLists, sysList):
    config = {'widgets': widgLists}
    for key in sysList:
        config[key] = sysList[key]
    convert(config)
    path = os.path.join(mydir, 'config.toml')
    with open(path, "w+") as config_file:
        config_file.write(toml.dumps(config))

####################################################
####################################################
####################################################

def initWidgets():
    widgetList = []
    for widg_conf in config['widgets']:
        if widg_conf['type'] == 'image':
            widgetList.append(widget.ImageWidget(cwidth, cheight, (widg_conf['posX'], widg_conf['posY']),
            (widg_conf['width'], widg_conf['height']), widg_conf['bwStyle'], widg_conf['scaleMode'],
            os.path.join(mydir, os.path.join('widgets/resources/images/', widg_conf['filename']))))
        if widg_conf['type'] == 'trello':
            widgetList.append(widget.TrelloWidget(cwidth, cheight, (widg_conf['posX'], widg_conf['posY']),
            (widg_conf['width'], widg_conf['height']), widg_conf['board'], widg_conf['list']))
    return widgetList

def drawWidget(w):
    coordX = w.cellX*cwidth
    coordY = w.cellY*cheight
    image_black.paste(im=w.image_black, mask=w.mask_black, box=(coordX, coordY))
    image_yellow.paste(w.image_yellow, (coordX, coordY))

def updateWidgets():
    for widg in widgetList:
        print("  updating trello widget")
        widg.updateWidget()
        print("")
    draw_black.rectangle(xy=((0,0), image_black.size), fill=255)
    draw_yellow.rectangle(xy=((0,0), image_yellow.size), fill=255)
    for widg in widgetList:
        drawWidget(widg)
    image_black.save(os.path.join(mydir, 'test/imgBlack.bmp'))
    image_yellow.save(os.path.join(mydir, 'test/imgYellow.bmp'))

widgetList = initWidgets()

####################################################
####################################################
####################################################

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