# SPDX-FileCopyrightText: 2025 Anne Barela for Adafruit Industries
#
# SPDX-License-Identifier: MIT
#
# Implement a tone function for CircuitPython I2C DACs

import sys
import array
import math
import time
import audiocore
from adafruit_fruitjam.peripherals import Peripherals

# Initialize Fruit Jam peripherals
fruit_jam = Peripherals(audio_output="speaker")  # or "headphone"
if fruit_jam.dac is None:
    print("\nAre you running this on a Fruit Jam?")
    sys.exit(1)

def tone(frequency, duration, volume=0.5):
    print(frequency, duration)
    """
    Play a tone at a specific frequency for a given duration.
    
    Args:
        frequency (int/float): Frequency in Hz (e.g., 440 for A4)
        duration (float): Duration in seconds
        volume (float): Volume level from 0.0 to 1.0 (default 0.5)
    """
    # Get the sample rate from the DAC
    sample_rate = fruit_jam.dac.sample_rate
    
    # Calculate length of one period of the waveform
    length = sample_rate // int(frequency)
    
    # Generate a sine wave for one period
    sine_wave = array.array("h", [0] * length)
    for i in range(length):
        sine_wave[i] = int((math.sin(math.pi * 2 * i / length)) * volume * (2**15 - 1))
    
    # Create a RawSample from the sine wave
    sine_wave_sample = audiocore.RawSample(sine_wave, sample_rate=sample_rate)
    
    # Play the tone
    fruit_jam.audio.play(sine_wave_sample, loop=True)
    time.sleep(duration)
    fruit_jam.audio.stop()


# Example usage:
if __name__ == "__main__":
    # Configure speaker settings
    fruit_jam.dac.speaker_output = True
    fruit_jam.dac.dac_volume = 0         # Digital volume (-63.5 to 24.0 dB)
    fruit_jam.dac.speaker_volume = -5    # Analog volume (-78.3 to 0 dB)
    fruit_jam.dac.speaker_gain = 18      # Amplifier gain (6, 12, 18, or 24 dB)
    
    # Play some tones
    tone(440, 1.0)      # A4 for 1 second
    time.sleep(0.2)     # Pause between tones
    tone(523, 0.5)      # C5 for 0.5 seconds
    time.sleep(0.2)
    tone(659, 0.75)     # E5 for 0.75 seconds
    
    # Example: play a melody
    notes = [
        (262, 0.5),  # C4
        (294, 0.5),  # D4
        (330, 0.5),  # E4
        (349, 0.5),  # F4
        (392, 1.0),  # G4
    ]
    
    for freq, dur in notes:
        tone(freq, dur, volume=0.5)
        time.sleep(0.1)