# Li'l Info Box Example Code
# Iffy Books 2025
# iffybooks.net/lil-info-box
# MicroPython code written for the Pi Pico. We recommend using the Thonny IDE!
from machine import Pin, I2C
import ssd1306
import time

led_pin = Pin(14, Pin.OUT)

## Set up OLED display
# Using GPIO pins 4 and 5 is required
i2c = I2C(id=0, sda=Pin(4), scl=Pin(5), freq=200000)
display = ssd1306.SSD1306_I2C(128, 64, i2c)

## Check current page
try:
    with open('current_page_number.txt') as fi:
        current_page_number = int(fi.read().strip())
        print("page no from disk: " + str(current_page_number))
except:
    with open('current_page_number.txt','w') as fo:
        fo.write('0')
    current_page_number = 0

text = '''THE OWLS.
Under the overhanging yews,
The dark owls sit in solemn state.
Like stranger gods; by twos and twos
Their red eyes gleam. They meditate.
Motionless thus they sit and dream
Until that melancholy hour
When, with the sun's last fading gleam,
The nightly shades assume their power.
From their still attitude the wise
Will learn with terror to despise
All tumult, movement, and unrest;
For he who follows every shade,
Carries the memory in his breast,
Of each unhappy journey made.
'''

## Replace common non-ASCII characters
text = text.replace('\n', ' ').replace('–','–').replace('—','–')
text = text.replace('“','"').replace('”','"')
text = text.replace('‘',"'").replace('’',"'")

lines = []

for i in range(int(len(text)/16)+1):
    lines.append(text[i*16:(i*16)+16].strip())

## Pad with extra lines at the end
padding_line_count = 6 - len(lines)%6
for i in range(padding_line_count):
    lines.append('')

## Create a list of lists, with each page represented as a list of 6 strings
pages_lol = list(zip(*(iter(lines),) * 6))


## Function for displaying a page
def show_page(j):
    page_list = pages_lol[j]
    display.fill(0)
    display.show()
    for i in range(6):
        display.text(page_list[i], 0, i*10, 1)
        display.show()
        time.sleep(0.05)

## Display current page
show_page(current_page_number)

## List of pins we'll use for the rotary encoder
# To add switches, add more Pin objects to this list
key_pin_array = [Pin(9, Pin.IN, Pin.PULL_UP), Pin(10, Pin.IN, Pin.PULL_UP)]

## Check for hardware input and update display
while True:
    # Check each pin
    for key_pin in key_pin_array:
        if not key_pin.value():  # Is it grounded?
            i = key_pin_array.index(key_pin)
            print('Pin ' + str(i) + ' is grounded')
            
            # Turn on the LED
            led_pin.value(1)
            
            # Wait for the pin to be ungrounded
            while not key_pin.value():
                pass
            
            # Rotary encoder action page back
            if i==0:
                if current_page_number <= 0:
                    current_page_number = 0
                else:
                    current_page_number-=1
                print(i)
                show_page(current_page_number)
                with open('current_page_number.txt','w') as fo:
                    fo.write(str(current_page_number))
                    
            # Rotary encoder action: page forward
            elif i==1:
                if current_page_number>=(len(pages_lol)-1):
                    current_page_number = len(pages_lol)-1
                else:
                    current_page_number+=1
                print(i)
                show_page(current_page_number)
                with open('current_page_number.txt','w') as fo:
                    fo.write(str(current_page_number))
            
                    
            # Turn off the LED
            led_pin.value(0)