#!/usr/bin/env python

from __future__ import print_function

import os
import sys
import codecs

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

from papirus import Papirus
from papirus import LM75B

# Force stdout to utf-8 even if redirected to pipe or file (e.g. when executed under cron)
if sys.version_info < (3,) :
    sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
else:
    sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer)

# 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()

# 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()

WHITE = 1
BLACK = 0

#FONT_FILE = '/usr/share/fonts/truetype/freefont/FreeMono.ttf'
FONT_FILE = '/usr/share/fonts/truetype/freefont/FreeSerif.ttf'

def main(argv):

    """main program - draw and display temperature"""

    papirus = Papirus(rotation = int(argv[0]) if len(sys.argv) > 1 else 0)
    papirus.clear()

    # initially set all white background
    image = Image.new('1', papirus.size, WHITE)

    # prepare for drawing
    draw = ImageDraw.Draw(image)
    width, height = image.size

    # base font size on mono spaced font
    font_size = int((width - 4) / (8 * 0.65))   # 8 chars to be displayed
    font = ImageFont.truetype(FONT_FILE, font_size)

    # get temperature
    sensor = LM75B()
    tempC = '{c:.2f}'.format(c=sensor.getTempCFloat()) + u" \u00b0" + 'C'
    tempF = '{c:.2f}'.format(c=sensor.getTempFFloat()) + u" \u00b0" + 'F'
    print('Temperature from LM75B: ' + tempC + ' - ' + tempF)

    # center the temperatures
    (txtwidth, txtheight) = draw.textsize(tempC, font=font)
    x = (width - txtwidth) / 2
    y = (height - 2 * txtheight - 10) / 2
    draw.rectangle((2, 2, width - 2, height - 2), fill=WHITE, outline=BLACK)
    draw.text((x, y), tempC, fill=BLACK, font=font)
    draw.text((x, y + txtheight + 5), tempF, fill=BLACK, font=font)

    papirus.display(image)
    papirus.update()

# main
if "__main__" == __name__:
    if len(sys.argv) < 1:
        sys.exit('usage: {p:s}'.format(p=sys.argv[0]))

    try:
        main(sys.argv[1:])
    except KeyboardInterrupt:
        sys.exit('interrupted')
        pass
