#!/usr/bin/env python

from __future__ import print_function

import os
import sys
import time
from papirus import Papirus
from PIL import Image, ImageMath
import argparse
from io import BytesIO

# Command line usage
# papirus-draw /path/to/image -t [resize | crop] -r [0 | 90 | 180 | 270] [-i]

# Running as root only needed for older Raspbians without /dev/gpiomem
if not (os.path.exists('/dev/gpiomem') and os.access('/dev/gpiomem', os.R_OK | os.W_OK)):
    user = os.getuid()
    if user != 0:
        print("Please run script as root")
        sys.exit()

# Check EPD_SIZE is defined
EPD_SIZE=0.0
if os.path.exists('/etc/default/epd-fuse'):
    exec(open('/etc/default/epd-fuse').read())
if EPD_SIZE == 0.0:
    print("Please select your screen size by running 'papirus-config'.")
    sys.exit()

def main():
    papirus = Papirus()
    p = argparse.ArgumentParser()
    p.add_argument('filepath', type=str)
    p.add_argument('--type', '-t',type=str, default="resize", help="Display type: crop or resize")
    p.add_argument('--rotation', '-r',type=int, default=0, help="Rotation one of 0, 90, 180, 270")
    p.add_argument('--invert', '-i',action='store_true', help="Invert image pixels")
    args = p.parse_args()
    papirus = Papirus(rotation = args.rotation)
    if args.filepath:
        print("Drawing on PaPiRus.......")
        draw_image(papirus, args.filepath, args.type, args.invert)

def draw_image(papirus, filepath, type, invert):
    message = ""
    # padding for placing the image
    xpadding = 0
    ypadding = 0
    # check whether to load the image from stdin or fs
    if (filepath == "-"):
        # load the image from stdin
        image = BytesIO(read_stdin())
    else:
        # load the image from fs
        image = filepath
    # open the image to display
    file = Image.open(image)
    # display with crop option
    if type == "crop":
        # Landscape image
        if file.size[0] > file.size[1]:
            wsize = int(float(papirus.size[1]) * float(float(file.size[0]) / float(file.size[1])))
            file.thumbnail((wsize, papirus.size[1]), Image.ANTIALIAS)
            message = "Landscape image cropped!"
        # Portrait image
        else:
            hsize = int(float(file.size[0]) * float(float(papirus.size[1]) / float(papirus.size[0])))
            file.thumbnail((papirus.size[0], hsize), Image.ANTIALIAS)
            message = "Portrait image cropped!"
    # display resize option
    else:
        # Landscape image
        if file.size[0] > file.size[1]:
            message = "Landscape image resized!"
        # Portrait image
        else:
            message = "Portrait image resized!"
        file.thumbnail(papirus.size, Image.ANTIALIAS)
    # centering the image
    xpadding = int((papirus.size[0] - file.size[0]) / 2)
    ypadding = int((papirus.size[1] - file.size[1]) / 2)
    # initially set all white background
    image = Image.new('1', papirus.size, 1)
    image.paste (file, (xpadding, ypadding))
    if invert:
        # Replace black with white pixels and vice versa
        image = ImageMath.eval('255-(a)', a=image)
    papirus.display(image)
    papirus.update()
    print(message)

def read_stdin():
    # Handle stdin differences between python2 and python3
    if sys.version_info >= (3, 0):
        stdin = sys.stdin.buffer
    else:
        stdin = sys.stdin
    return stdin.read()

if __name__ == '__main__':
    main()
