from machine import I2C, Pin, UART
from gpio_lcd import GpioLcd
import time
import ds1307
lcd = GpioLcd(rs_pin=Pin(16),
          enable_pin=Pin(17),
          d4_pin=Pin(18),
          d5_pin=Pin(19),
          d6_pin=Pin(20),
          d7_pin=Pin(21),
          num_lines=2,
          num_columns=16
          )
i2c = I2C(0, scl=Pin(9), sda=Pin(8))
rtc = ds1307.DS1307(i2c, 0x68)

csv_filename = "data.csv"

with open(csv_filename, "a") as v:
    v.write("TOKEN,PRESS_TIME,CALL_TIME\n")
    v.close()


# Segment pins
a = Pin(0, Pin.OUT)
b = Pin(1, Pin.OUT)
c = Pin(2, Pin.OUT)
d = Pin(3, Pin.OUT)
e = Pin(4, Pin.OUT)
f = Pin(5, Pin.OUT)
g = Pin(6, Pin.OUT)

# Button pin
button = Pin(10, Pin.IN, Pin.PULL_DOWN)
button1 = Pin(11,Pin.IN,Pin.PULL_DOWN)
led = Pin(15,Pin.OUT)
# Digit patterns (0–9) for common cathode
digit_patterns = [
    [1,1,1,1,1,1,0],  # 0
    [0,1,1,0,0,0,0],  # 1
    [1,1,0,1,1,0,1],  # 2
    [1,1,1,1,0,0,1],  # 3
    [0,1,1,0,0,1,1],  # 4
    [1,0,1,1,0,1,1],  # 5
    [1,0,1,1,1,1,1],  # 6
    [1,1,1,0,0,0,0],  # 7
    [1,1,1,1,1,1,1],  # 8
    [1,1,1,1,0,1,1],  # 9
]

# Function to display a digit
def display_digit(num):
    pattern = digit_patterns[num]
    a.value(pattern[0])
    b.value(pattern[1])
    c.value(pattern[2])
    d.value(pattern[3])
    e.value(pattern[4])
    f.value(pattern[5])
    g.value(pattern[6])

# Initial state
current = 0
display_digit(current)
count1 = 0
while True:
    date_time = rtc.datetime
    date_str = "{:02d}/{:02d}/{:04d}".format(date_time[2], date_time[1], date_time[0])
    time_str = "{:02d}:{:02d}:{:02d}".format(date_time[3], date_time[4], date_time[5])
    lcd.move_to(0,0)
    lcd.putstr("PRESS BUTTON ")
    lcd.move_to(1,1)
    x = button1.value()
    state = button.value()

    if(x==1):
        count1 = count1 + 1
        lcd.clear()
        lcd.putstr("TOKEN :" + str(count1))
        with open(csv_filename, "a") as v:
            line = "{},{}\n".format(count1,time_str)
            v.write(line)
            print(line.strip())
            v.close()
        time.sleep(1)
        lcd.clear()

    if state == 1 and current < count1:  # Call button pressed
        current = (current + 1) % 10
        display_digit(current)
        led.value(1)
        time.sleep(0.2)
        led.value(0)
        time.sleep(0.2)

    
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT
GND5VSDASCLSQWRTCDS1307+