#!/usr/bin/python3

import time
import subprocess
import signal
import os

from board import SCL, SDA
import busio
from PIL import Image, ImageDraw, ImageFont
import adafruit_ssd1306

def sighandler(signum, frame):
    global width, height, x, top, fs, image, draw, disp, font

    draw.rectangle((0, 0, width, height), outline=0, fill=0)
    draw.text((x, top+fs*2), "    Tschüss...", font=font, fill=255)
    disp.image(image)
    disp.show()
    raise SystemExit

# Create the I2C interface.
i2c = busio.I2C(SCL, SDA)

# Create the SSD1306 OLED class.
# The first two parameters are the pixel width and pixel height.
# Change these to the right size for your display!
disp = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c)

# Clear display.
disp.fill(0)
disp.show()

# Create blank image for drawing.
# Make sure to create image with mode '1' for 1-bit color.
width = disp.width
height = disp.height
image = Image.new("1", (width, height))

# Get drawing object to draw on image.
draw = ImageDraw.Draw(image)

# Draw a black filled box to clear the image.
draw.rectangle((0, 0, width, height), outline=0, fill=0)

# Draw some shapes.
# First define some constants to allow easy resizing of shapes.
padding = -2
top = padding
bottom = height - padding
# Move left to right keeping track of the current x position for drawing shapes.
x = 0

# Load default font.
#font = ImageFont.load_default()

# Alternatively load a TTF font.  Make sure the .ttf font file is in the
# same directory as the python script!
# Some other nice fonts to try: http://www.dafont.com/bitmap.php
fs = 12
font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', fs)

signal.signal(signal.SIGTERM, sighandler)
signal.signal(signal.SIGQUIT, sighandler)
signal.signal(signal.SIGHUP, sighandler)
signal.signal(signal.SIGINT, sighandler)

try:
    while True:
        try:
            HOST = subprocess.check_output("hostname -I",
                                           timeout=1, shell = True)
        except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
            HOST = ""
        try:
            s = str(HOST, "UTF-8")
            ip = s.split()[0]
        except (TypeError, IndexError):
            ip = ""

        try:
            UPT = subprocess.check_output("uptime", timeout=1, shell = True )
        except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
            UPT = ""
        try:
            s = str(UPT, "UTF-8")
            lupt = s.split()
            tim = lupt[0]
            upt = lupt[2].rstrip(",")
            cpu = lupt[8].rstrip(",")
        except (TypeError, IndexError):
            upt = ""
            cpu = ""

        try:
            TEM = subprocess.check_output("vcgencmd measure_temp",
                                          timeout=1, shell = True )
        except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
            TEM = ""
        try:
            s = str(TEM, "UTF-8")
            temp = s.split("=")[1]
        except (TypeError, IndexError):
            temp = ""

        try:
            MemUsage = subprocess.check_output("free -m",
                                               timeout=1, shell = True )
        except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
            MemUsage = ""
        try:
            s = str(MemUsage, "UTF-8")
            lmem = s.partition("Mem:")[2].split()
            fmem = lmem[1]
            tmem = lmem[0]
        except (TypeError, IndexError):
            fmem = ""
            tmem = ""

        try:
            Disk = subprocess.check_output("df -h",
                                           timeout=1, shell = True )
        except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
            Disk  = ""
        try:
            s  = str(Disk, "UTF-8")
            ld = s.partition("\n")[2]
            ldisk = ld.split()
            use   = ldisk[2].rstrip("G")
            size  = ldisk[1]
        except (TypeError, IndexError):
            use  = ""
            size = ""

        try:
            with open('/run/lock/dds', encoding="utf-8") as fd:
                dds = fd.readline()
                fd.close()
        except FileNotFoundError:
            dds = "" 

        # Draw a black filled box to clear the image.
        draw.rectangle((0, 0, width, height), outline=0, fill=0)

        # Write four lines of text.
        if(dds != ""):
            draw.text((x, top), dds, font=font, fill=255)
        else:
            draw.text((x, top), "IP: " + ip, font=font, fill=255)
        draw.text((x, top+fs+3), "CPU: " + cpu + " " + temp, font=font, fill=255)
        draw.text((x, top+fs*2+3), "RAM: " + fmem + " / " + tmem + "M", font=font, fill=255)
        draw.text((x, top+fs*3+3), "SD: " + use + " / " + size, font=font, fill=255)
        draw.text((x, top+fs*4+3), "   " + tim + "  " + upt, font=font, fill=255)

        # Display image.
        disp.image(image)
        disp.show()
        time.sleep(0.5)

except KeyboardInterrupt:
        sighandler()
