#!/usr/bin/python
import sys
import os
script_dir = os.path.dirname(os.path.abspath(__file__))
lib_dir = os.path.join(script_dir, '..', 'lib')
sys.path.append(lib_dir)
import time
import argparse
from lib.sheogorath import Sheogorath
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()

# Only load actual drivers when not in debug mode
if not args.debug:
    from lib import epd2in13_V2
    epd = epd2in13_V2.EPD()

app = 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:
    epd.exit()
    exit()
