import as7265x
import smbus
import numpy as np
import os
from datetime import datetime
import RPi.GPIO as GPIO
import time


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

'''Alphabetical order is not spectral order. ie
A,B,C,D,E,F,G,H,I,J,K,L,R,S,T,U,V,W .
According to the data sheets, the spectral order is
A,B,C,D,E,F,G,H,R,I,S,J,T,U,V,W,K,L.

The order in the example reflects the UV to NIR spectral order.
'''


# 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

# Define Path/Label
folder = "Ideal"




def scan() -> None:
    """"
    Scan function use to scan using AS7265X and save the data into a txt in a folder based
    on its label.

    """

    
    # 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 = []
    data.append(sensor.getCalibratedA())
    data.append(sensor.getCalibratedB())
    data.append(sensor.getCalibratedC())
    data.append(sensor.getCalibratedD())
    data.append(sensor.getCalibratedE())
    data.append(sensor.getCalibratedF())
    data.append(sensor.getCalibratedG())
    data.append(sensor.getCalibratedH())
    data.append(sensor.getCalibratedR())        
    data.append(sensor.getCalibratedI())
    data.append(sensor.getCalibratedS())
    data.append(sensor.getCalibratedJ())
    data.append(sensor.getCalibratedT())
    data.append(sensor.getCalibratedU())
    data.append(sensor.getCalibratedV())
    data.append(sensor.getCalibratedW())
    data.append(sensor.getCalibratedK())
    data.append(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)


def save_data(data: list) -> None:
    """"
    Save a list into a txt, and put the txt on the folder based on defined path.
    """

    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}")

print("Setup completed!")
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!")
        time.sleep(0.15)  # Delay untuk menghindari pembacaan terlalu cepat
except KeyboardInterrupt:
    print("Program dihentikan.")
finally:
    GPIO.cleanup()
