#! /home/pi/env/blinka/bin/python3

import adafruit_ssd1306
import board
import busio
import digitalio
import json
import math
import requests
import signal
import subprocess
import sys
import time
from PIL import Image, ImageDraw, ImageFont

i2c = busio.I2C(board.SCL, board.SDA)
disp = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3D)
disp.fill(0)
disp.show()
width = disp.width
height = disp.height
image = Image.new("1", (width, height))
draw = ImageDraw.Draw(image)
draw.rectangle((0, 0, width, height), outline=0, fill=0)
padding = 0 
top = padding
bottom = height - padding
x = 2
font = ImageFont.load_default()

def handler(signum = None, frame = None):
    print('-------------------')
    print('turning off display')
    print('-------------------')
    clearDisplay()
    sys.exit(0)

def clearDisplay():
    draw.rectangle((0, 0, width, height), outline=0, fill=0)
    disp.image(image)
    disp.show()

for sig in [signal.SIGTERM, signal.SIGQUIT]:
    signal.signal(sig, handler)

def run():
    global outsideTemp, currentTime, previousTime
    #print(pos)
    draw.rectangle((0, 0, width, height), outline=0, fill=0)
    cmd = "hostname -I | cut -d' ' -f1"
    IP = subprocess.check_output(cmd, shell=True).decode("utf-8")
    cmd = 'vcgencmd measure_temp'
    Temp = subprocess.check_output(cmd, shell=True).decode("utf-8")
    tempStr = Temp.replace('temp=', '')
    cmd = 'vcgencmd measure_clock arm'
    Freq = subprocess.check_output(cmd, shell=True).decode("utf-8")
    Freq = Freq.replace('frequency(0)=', '')
    freqNum = int(Freq) / 1000000000
    freqNum2 = format(freqNum, '.1f') + " GHz"

    ipList = IP.split('.')
    ip1 = '.'.join(map(str, ipList[:2]))
    if (ip1 != ''):
        ip1 = ip1 + '.'
    ip2 = '.'.join(map(str, ipList[2:]))

    draw.text((35, 0), ip1, font=font, fill=255)
    draw.text((35, 10), ip2, font=font, fill=255)
    draw.text((35, 25), tempStr, font=font, fill=255)
    draw.text((35, 40), freqNum2, font=font, fill=255)

    disp.image(image.rotate(90))
    disp.show()
    time.sleep(0.1)

while True:
    try:
        run()
    except KeyboardInterrupt:
        clearDisplay()
        print()
        sys.exit(0)
    except Exception:
        clearDisplay()
        print()
        sys.exit(0)