import board
from board import SCL, SDA
import busio
import random
import time

# Import the PCA9685 module.
from adafruit_pca9685 import PCA9685

import adafruit_dotstar


pixels = adafruit_dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1)
pixels[0] = (0, 0, 0)

# these are the same no matter which preset we use
MAX = 60000
MIN = 2000

#presets = [dict(increment=1000, sleepFor=1000), dict(increment=500, sleepFor=5000)]
presets = [dict(increment=1000, sleepFor=1000)]

# Create the I2C bus interface.
i2c_bus = busio.I2C(SCL, SDA)
# Create a simple PCA9685 class instance.
pca = PCA9685(i2c_bus)
# Set the PWM frequency to 60hz.
pca.frequency = 60

numLedStrands = 12

# create the array of breaths.
breaths = []
def init():
    for i in range(0, numLedStrands):
        nextBreath = dict(
            index = i,
            preset = 0, 
            curValue = 0, 
            goingUp = True,
            isDone = True, 
            nextBreathDelay = random.uniform(1, 5),
            lastBreath = time.monotonic())
        breaths.append(nextBreath)
        pca.channels[i].duty_cycle = 0


def breathing(breath):
    if (breath["isDone"] == False):
        if (breath["goingUp"] == True):
            if (breath["curValue"] + presets[breath["preset"]]["increment"] <= MAX):
                breath["curValue"] += presets[breath["preset"]]["increment"]
                pca.channels[breath["index"]].duty_cycle = breath["curValue"]
            else:
                breath["goingUp"] = False
        else:
            if (breath["curValue"] - presets[breath["preset"]]["increment"] >= MIN):
                breath["curValue"] -= presets[breath["preset"]]["increment"]
                pca.channels[breath["index"]].duty_cycle = breath["curValue"]
            else:
                breath["isDone"] = True
                breath["nextBreathDelay"] = random.uniform(1, 5)
                breath["lastBreath"] = time.monotonic()
    else:
        if (time.monotonic() - breath["lastBreath"] >= breath["nextBreathDelay"]):
            breath["isDone"] = False
            breath["preset"] = random.randint(0, len(presets) - 1)
            breath["goingUp"] = True


init()

while True:
    for breath in breaths:
        breathing(breath)