import sys
import os
import subprocess
import logging
import epd2in13_V3
import time
from PIL import Image, ImageDraw, ImageFont

picdir = os.path.dirname(os.path.realpath(__file__))
libdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib')
if os.path.exists(libdir):
    sys.path.append(libdir)

logging.basicConfig(level=logging.DEBUG)

def get_wifi_status():
    try:
        # Get the SSID of the currently connected Wi-Fi network
        result = subprocess.run(['iwgetid', '-r'], capture_output=True, text=True)
        ssid = result.stdout.strip()
        if ssid:
            return "OK", ssid
        else:
            return "Disconnected", "N/A"
    except Exception as e:
        return "Error", str(e)

def main():
    try:
        logging.info("epd2in13_V3 datetime and network info")

        epd = epd2in13_V3.EPD()
        logging.info("init and Clear")
        epd.init()
        epd.Clear(0xFF)

        # Load fonts
        font18 = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', 18)
        font16 = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', 14)

        clock_refresh_interval = 5  # Refresh every 5 seconds
        motd_refresh_interval = 120  # Refresh every minute

        time_image = Image.new('1', (epd.height, epd.width), 255)
        draw = ImageDraw.Draw(time_image)

        previous_clock_time = ''
        previous_date = ''
        previous_status = ''
        previous_ssid = ''
        previous_footer_refresh = 0

        while True:
            # Get current time and date
            current_time = time.strftime('%l:%M %p').lstrip().lower()
            current_date = time.strftime('%a, %b %d, \'%y')

            # Get network status and SSID
            status, ssid = get_wifi_status()

            # If time, date, status, or SSID has changed, update
            if current_time != previous_clock_time or current_date != previous_date or status != previous_status or ssid != previous_ssid:
                # Clear and redraw only if there's a change
                if status != previous_status or ssid != previous_ssid:
                    draw.rectangle((0, 0, 250, 40), fill=255)  # Clear network status and SSID area
                    draw.text((0, 0), f"CONNECTION: {status}", font=font18, fill=0)
                    draw.text((0, 20), f"SSID: {ssid}", font=font18, fill=0)
                    epd.displayPartial(epd.getbuffer(time_image.rotate(180)))  # Partial refresh for status and SSID

                # Update the time and date with partial refresh
                if current_time != previous_clock_time or current_date != previous_date:
                    draw.rectangle((0, 40, 250, 80), fill=255)  # Clear time and date area
                    draw.text((0, 40), current_time, font=font18, fill=0)
                    draw.text((0, 60), current_date, font=font18, fill=0)
                    epd.displayPartial(epd.getbuffer(time_image.rotate(180)))  # Partial refresh for time and date

                # Only refresh footer every minute
                if time.time() - previous_footer_refresh >= motd_refresh_interval:
                    draw.rectangle((0, 90, 250, 122), fill=255)  # Clear footer area
                    draw.text((0, 100), "DO NOT UNPLUG | rintyuu.dev", font=font16, fill=0)
                    epd.displayPartial(epd.getbuffer(time_image.rotate(180)))  # Partial refresh for footer
                    previous_footer_refresh = time.time()

                # Update previous values
                previous_clock_time = current_time
                previous_date = current_date
                previous_status = status
                previous_ssid = ssid

            # Wait for the interval before refreshing
            time.sleep(clock_refresh_interval)

    except IOError as e:
        logging.info(e)

    except KeyboardInterrupt:
        logging.info("ctrl + c:")
        epd2in13_V3.epdconfig.module_exit()
        exit()

if __name__ == "__main__":
    main()
