from PIL import Image, ImageDraw, ImageFont, ImageOps
import re
import time
import widgets.widget as widget
import argparse
import os
import toml
try:
    import drivers.epd7in5b
    testMode = False
except:
    testMode = True

mydir = os.path.dirname(os.path.abspath(__file__))

parser = argparse.ArgumentParser(description="NotiFrame display")
parser.add_argument('-t', '--test', help='enable test mode', action='store_true')
args = parser.parse_args()
if args.test:
    testMode = True

print("RUNNING IN TESTMODE: "+str(testMode))

if not testMode:
    epd = epd7in5b.EPD()
    epd.init()

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:'}
]}

#print(toml.dumps(config))
print(config)
print(config2)

cwidth = int(round(config['resWidth']/config['cellsWidth']))
cheight = int(round(config['resHeight']/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)

#str1 = open("text.txt", "r").read()
#str2 = open("text.txt", "r").read()
#str3 = open("text.txt", "r").read()
#strList = []
#strList.append(str1)
#strList.append(str2)
#strList.append(str3)

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']))

    #widgetList.append(widget.ImageWidget(cwidth, cheight, (0, 0), (3, 3), "mono", "fill", os.path.join(mydir, os.path.join('widgets/resources/images/', 'forest.jpg'))))
    #widgetList.append(widget.TrelloWidget(cwidth, cheight, (0, 0), (1, 3), "Organisation", "Plans"))
    #widgetList.append(widget.TrelloWidget(cwidth, cheight, (1, 0), (2, 3), "E-paper", "Done"))
    #widgetList.append(widget.ImageWidget(cwidth, cheight, (1, 2), (2, 1), "mono", "fill", "forest.jpg"))
    #widgetList.append(widget.TextWidget(cwidth, cheight, (0, 0), (1, 3), str2))
    #widgetList.append(widget.TextWidget(cwidth, cheight, (0, 0), (2, 3), str1))
    #widgetList.append(widget.ImageWidget(cwidth, cheight, (1, 0), (1, 3), "mono", "fill", "g.jpg"))
    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 render(index):
	if index is not 0:
		for widg in widgetList:
			widg.updateWidget()
	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)
	if not testMode:
		epd.display_frame(epd.get_frame_buffer(image_black),epd.get_frame_buffer(image_yellow))
	else:
		image_black.save(os.path.join(mydir, 'test/imgBlack.bmp'))
		image_yellow.save(os.path.join(mydir, 'test/imgYellow.bmp'))

widgetList = initWidgets()
i = 0
while(True):
    print("RENDERING "+str(i))
    render(i)
    i = (i + 1)
    #time.sleep(10)
