import os
print(os.listdir('/'))
import time, board, digitalio, random, neopixel
from adafruit_debouncer import Button
from audiomp3 import MP3Decoder
from audiopwmio import PWMAudioOut as AudioOut

class Button:
    def __init__(self, pin):
        self.pin = pin

    @property
    def value(self):
        return not self.pin.value


#Define the Led pin
led_pin=board.GP1
#Initialize the LED pin as a digital output
led=digitalio.DigitalInOut(led_pin)
led.direction=digitalio.Direction.OUTPUT

BRIGHTNESS = 0.8  # Adjust the overall brightness (0.0 to 1.0)
GLOW_FACTOR = 90  # Adjust the intensity of the glow effect

# PIN 1
#audio = AudioOut(board.GP1)
path = "sounds/"

# PIN 15
button_input = digitalio.DigitalInOut(board.GP15)
button_input.switch_to_input(digitalio.Pull.UP)
piezo_button = Button(button_input)

filename = "fire.mp3"

# Initialize variables for counting button presses
initial_press_count = 2
press_count = initial_press_count
last_press_time = 0

# Define NeoPixel parameters for multiple strips
LED_PIN_1 = board.GP6
NUM_LEDS_1 = 120
pixels_1 = neopixel.NeoPixel(LED_PIN_1, NUM_LEDS_1, brightness=BRIGHTNESS, auto_write=False)

LED_PIN_2 = board.GP7  # Change to the appropriate pin for the second strip
NUM_LEDS_2 = 30  # Change to the appropriate number of LEDs for the second strip
pixels_2 = neopixel.NeoPixel(LED_PIN_2, NUM_LEDS_2, brightness=BRIGHTNESS, auto_write=False)

def play_mp3(filename, duration):
    mp3_file = open(path + filename, "rb")
    decoder = MP3Decoder(mp3_file)
    audio.play(decoder)

    start_time = time.monotonic()
    while time.monotonic() - start_time < duration:
        # Calculate fade-out effect
        fade_out_duration = 1.0  # 1 second fade-out
        elapsed_time = time.monotonic() - start_time
        if elapsed_time > duration - fade_out_duration:
            # Apply fade-out effect
            fade_out_progress = (elapsed_time - (duration - fade_out_duration)) / fade_out_duration
            audio.volume = 1.0 - fade_out_progress
        else:
            audio.volume = 1.0

    # Reset the volume and wait for any lingering audio to finish
    audio.volume = 1.0
    while audio.playing:
        pass

def fire_effect(pixels, animation_duration):
    num_leds = len(pixels)
    start_time = time.monotonic()

    # Define parameters for fire particles
    num_particles = 10  # Adjust the number of fire particles
    particles = [{'position': random.randint(0, num_leds - 1), 'brightness': 255} for _ in range(num_particles)]

    # Run the fire effect for the specified duration
    while time.monotonic() - start_time < animation_duration - 1:
        # Simulate fire colors with variations
        palette = [(255, 180, 0), (255, 120, 0), (255, 60, 0), (255, 0, 0)]

        # Update each fire particle
        for particle in particles:
            # Set fire color for the particle
            color = tuple(int(val * particle['brightness'] / 255) for val in palette[random.randint(0, len(palette) - 1)])
            pixels[particle['position']] = color

            # Spread the intensity to neighboring LEDs (glow effect)
            for i in range(particle['position'] - 2, particle['position'] + 3):
                index = i % num_leds
                pixels[index] = tuple(int(val / GLOW_FACTOR) for val in pixels[index])

            # Occasionally reduce brightness for fading effect
            if random.randint(0, 9) < 2:
                particle['brightness'] = max(0, particle['brightness'] - 5)

            # Occasionally move the particle
            if random.randint(0, 9) < 2:
                particle['position'] += random.choice([-1, 1])
                particle['position'] %= num_leds  # Ensure the position stays within the strip

                # If the particle moves, increase its brightness
                particle['brightness'] = min(255, particle['brightness'] + 20)

        pixels.show()
        time.sleep(0.1)  # Adjust the delay time for speed

    # Fade out during the last 1 second
    start_fade_out_time = time.monotonic()
    while time.monotonic() - start_fade_out_time < 1:
        fade_out_progress = (time.monotonic() - start_fade_out_time) / 1.0
        for i in range(num_leds):
            pixels[i] = tuple(int(val * (1.0 - fade_out_progress)) for val in pixels[i])
        pixels.show()
        
while True:
    if piezo_button.value:
        press_count = 6
        led.value=True #Wait for 1 second 
        print("LED ON!")
        time.sleep(1)  #waitfor 1 second
        led.value=False #Turn the LED off
        print("LED OFF!")
        time.sleep(1)   #Wait for 1 second
        fire_effect(pixels_1, press_count)

        # Button is pressed
        current_time = time.monotonic()

        # Check if it's within a 1-second window since the last press
        if current_time - last_press_time < 1:
            # Increment the press count
            press_count += 1
        else:
            # Play the MP3 file if there was a 1-second pause in button presses
            if press_count > initial_press_count:
                print(f"Button Press Count: {press_count}")
                #play_mp3(filename, press_count)
                fire_effect(pixels_1, press_count)
                fire_effect(pixels_2, press_count)
                press_count = 0  # Reset the press count

        # Update the last press time
        last_press_time = current_time

    # Add a small delay to avoid rapid polling
    time.sleep(0.1)


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