#!/usr/bin/python
# -*- coding:utf-8 -*-
import sys
import os
import time
import traceback
import argparse
from random import randint, choice
from PIL import Image,ImageDraw,ImageFont,ImageShow
from lib import application
from lib import epdummy

parser = argparse.ArgumentParser(description='e-Ink Sheogorath')
parser.add_argument('--debug', action='store_true', help='If true, does not initialize e-Ink, shows images in window')
parser.add_argument('-d', '--delay', default=45, help='Delay between frames in seconds')
parser.add_argument('-r', '--refresh', default=10, help='Amount of frames after which to refresh the screen')
args = parser.parse_args()

epd = epdummy.EPDummy()
if not args.debug:
    from lib import epd2in13_V2
    epd = epd2in13_V2.EPD()

app = application.Sheogorath()

try:
    DELAY = int(args.delay)
except ValueError:
    DELAY = 45
try:
    N_REFRESH = int(args.refresh)
except ValueError:
    N_REFRESH = 10

try:
    epd.init(epd.FULL_UPDATE)
    epd.Clear(0xFF)
    
    # read bmp file on window
    epd.Clear(0xFF)

    epd.init(epd.PART_UPDATE)
    n = 0
    while (True):
        n += 1
        if n is N_REFRESH:
            epd.init(epd.FULL_UPDATE)
            epd.Clear(0xFF)
            epd.Clear(0xFF)
            n = 0
            time.sleep(1)
            epd.init(epd.PART_UPDATE)
        frame = epd.getbuffer(app.get_frame())
        epd.displayPartial(frame)
        epd.displayPartial(frame)
        time.sleep(DELAY)
except KeyboardInterrupt:
    if not args.debug:
        epd2in13_V2.epdconfig.module_exit(cleanup=True)
    exit()
