import as7265x
import smbus
import numpy as np
import os
from datetime import datetime
import RPi.GPIO as GPIO
import time
from luma.core.interface.serial import i2c
from luma.oled.device import ssd1306
from luma.core.render import canvas
from PIL import ImageFont

# AS7265X Configuration
i2c_bus = smbus.SMBus(1)
sensor = as7265x.AS7265X(i2c_bus)
x = ['410', '435', '460', '485', '510', '535', '560', '585',
     '610', '645', '680', '705', '730', '760', '810', '860',
     '900', '940']

# Button GPIO Configuration
BUTTON_PIN = 22  # Button use pin 22
GPIO.setmode(GPIO.BCM)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)  # Pull-down resistor

# OLED Configuration
OLED_ADDRESS = 0x3C  # I2C address of the OLED
serial = i2c(port=1, address=OLED_ADDRESS)
oled = ssd1306(serial)

# Load font (optional, system fonts or custom fonts can be used)
font_path = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
font = ImageFont.truetype(font_path, 12) if os.path.exists(font_path) else None

# Define Path/Label
folder = input("Masukkan Label: ")

def scan() -> None:
    """Scan function using AS7265X and save data to a file."""
    # Turn on all LED
    sensor.begin()
    sensor.enableBulb(as7265x.LED_WHITE)
    sensor.enableBulb(as7265x.LED_IR)
    sensor.enableBulb(as7265x.LED_UV)
    sensor.setIntegrationCycles(1)

    # Take measurements
    sensor.takeMeasurements()

    data = [
        sensor.getCalibratedA(), sensor.getCalibratedB(), sensor.getCalibratedC(), sensor.getCalibratedD(),
        sensor.getCalibratedE(), sensor.getCalibratedF(), sensor.getCalibratedG(), sensor.getCalibratedH(),
        sensor.getCalibratedR(), sensor.getCalibratedI(), sensor.getCalibratedS(), sensor.getCalibratedJ(),
        sensor.getCalibratedT(), sensor.getCalibratedU(), sensor.getCalibratedV(), sensor.getCalibratedW(),
        sensor.getCalibratedK(), sensor.getCalibratedL()
    ]

    sensor.disableBulb(as7265x.LED_WHITE)
    sensor.disableBulb(as7265x.LED_IR)
    sensor.disableBulb(as7265x.LED_UV)

    # Save data as txt file
    save_data(data)
    display_message("Scan succeed!")

def save_data(data: list) -> None:
    """Save a list into a txt file in the defined folder."""
    filename = datetime.now().strftime("%Y-%m-%d-%H:%M:%S") + ".txt"
    if not os.path.exists(folder):
        os.makedirs(folder)

    file_path = os.path.join(folder, filename)
    with open(file_path, "w") as file:
        for item in data:
            file.write(f"{item};")

    print(f"List telah disimpan ke {file_path}")

def display_message(message: str) -> None:
    """Display a message on the OLED."""
    with canvas(oled) as draw:
        draw.text((10, 25), message, fill="white", font=font)
    time.sleep(2)  # Display message for 2 seconds

def scan_message():
    with canvas(oled) as draw:
        draw.text((5,5), "Push button", fill='white', font=font)
        draw.text((5,25), "to scan!", fill='white', font=font)
    time.sleep(2)

print("Setup completed!")
display_message("Setup Completed!")
scan_message()
print("=" * 20)
print("Push a button to scan!")

try:
    while True:
        if GPIO.input(BUTTON_PIN) == GPIO.HIGH:
            print("Tombol ditekan!")
            print("Memulai scan....")
            scan()
            print("Scan berhasil!")
            scan_message()
            
        time.sleep(0.1)  # Delay untuk menghindari pembacaan terlalu cepat
except KeyboardInterrupt:
    print("Program dihentikan.")
finally:
    GPIO.cleanup()
