#!/usr/bin/env perl
use strict;
use warnings;

use lib '/Users/gene/sandbox/MIDI-Drummer-Tiny/lib';
use MIDI::Drummer::Tiny; # https://metacpan.org/pod/MIDI::Drummer::Tiny
use lib '/Users/gene/sandbox/MIDI-Util/lib';
use MIDI::Util; # https://metacpan.org/pod/MIDI::Util
use Music::Duration::Partition;
use Music::Scales;
use Music::Voss qw/ powers /;

my $size = shift || 4;
my $max  = shift || 8;
my $bpm  = shift || 90;

my $score = MIDI::Util::setup_score( bpm => $bpm );

$score->synch(
    \&melody,
    \&beat,
);

$score->write_score("$0.mid");

sub beat {
    my $d = MIDI::Drummer::Tiny->new( bpm => $bpm, score => $score );

    for my $n ( 0 .. $size * $max * 2 - 1 ) {
        $d->note( $d->quarter, $d->closed_hh );
    }
}

sub melody {
    my $mdp = Music::Duration::Partition->new(
        size => $size,
#        pool => [qw/ qn en ddsn dsn ten sn tsn /],
        pool => [qw/ qn en sn /],
    );

    my $motif = $mdp->motif;
#use Data::Dumper;warn(__PACKAGE__,' ',__LINE__," MARK: ",Dumper$motif);exit;

    my ( $scale, $genf ) = get_genf( 'A', 5, 'minor' );

    for my $i ( 1 .. $max ) {
        my @notes = map { $scale->[ $genf->($_) % @$scale ] } 0 .. @$motif - 1;
#use Data::Dumper;warn(__PACKAGE__,' ',__LINE__," MARK: ",Dumper\@notes);exit;

        for my $n ( 0 .. @notes - 1 ) {
            $score->n( $motif->[$n], $notes[$n] );
        }

        $score->r('wn');
    }
}

sub get_genf {
    my ( $note, $octave, $type ) = @_;

    my @scale = map { $_ . $octave } get_scale_notes( $note, $type );
    # Transform to MIDI accidentals
    for ( @scale ) {
        s/#/s/;
        s/b/f/;
    }

    my $seed = [ map { sub { int rand 2 } } @scale ];
    my $genf = powers( calls => $seed );

    return \@scale, $genf;
}
