#!/usr/bin/env python
# Euclidean Rhythm Visualizations (requires Pillow and py3)
from random import randint
from math import floor

from PIL import Image
from PIL.ImageColor import getrgb

from euclidean import euclidean_rhythm
from drawing import GenImage


def visualize_it(beats, pulses):
    width = 600
    height = 20
    title = 'er_one_strip_{0}_{1}'.format(beats, pulses)

    gi = GenImage((width, height), title, timestamped=False)

    with gi.draw() as d:
        er = euclidean_rhythm(beats, pulses)
        w = width / len(er)
        offset = 0
        d.rectangle(((0,0), (width, height)), (0, 0, 55, 180))
        for v in er:
            if v > 0:
                d.rectangle([(offset, 0), (offset + w, height)], (200,0,55,128))
            offset += w

    gi.save()


# visualize_it(4, 2)
# visualize_it(6, 3)
# visualize_it(7, 3)
# visualize_it(8, 3)
# visualize_it(9, 4)
# visualize_it(15, 4)

def visualize_many(rhythms, width, height, title='er_visualize_many', timestamped=False):
    h = height / len(rhythms)

    gi = GenImage((width, height), title, timestamped=timestamped)

    with gi.draw() as d:
        height_offset = 0
        d.rectangle(((0,0), (width, height)), (0, 0, 55, 180))
        for i, er in enumerate(rhythms):
            beats = len(er)
            w = width / beats
            offset = 0
            for v in er:
                if v > 0:
                    d.rectangle([(offset, height_offset), (offset + w, height_offset + h)], (200, 0, 55, 128))
                offset += w

            height_offset += h

    gi.save()


def randpair(maxrand):
    pulses = randint(0, maxrand)
    beats = pulses + randint(1, maxrand)
    return (beats, pulses)


stacked_same_beat = (
    euclidean_rhythm(16, 2),
    euclidean_rhythm(16, 4),
    euclidean_rhythm(16, 6),
    euclidean_rhythm(16, 8),
    euclidean_rhythm(16, 6),
    euclidean_rhythm(16, 4),
    euclidean_rhythm(16, 2)
)


visualize_many(stacked_same_beat, 600, 600, 'er_stacked_same_beats')


a1 = randint(0, 3)
a2 = randint(0, 5)
a3 = randint(0, 6)


stacked_same_beat = (
    euclidean_rhythm(16, a1),
    euclidean_rhythm(16, a2),
    euclidean_rhythm(16, a3),
    euclidean_rhythm(16, randint(0, 16)),
    euclidean_rhythm(16, a3),
    euclidean_rhythm(16, a2),
    euclidean_rhythm(16, a1)
)

visualize_many(stacked_same_beat, 600, 600, 'er_stacked_same_beat_rand')

visualize_many([euclidean_rhythm(*randpair(randint(3, 23))) for _ in range(20)], 600, 600, 'er_visualize_many')

visualize_many([euclidean_rhythm(*randpair(randint(3, 23))) for _ in range(10)], 600, 50, 'er_visualize_many_strip')
