
var onlyFullyRated = true;  // if true, omits any albums that have unrated songs
var minTracks = 6;          // minimum number of tracks that an album must have to be counted in the final output
var minSongLength = 120;    // length in seconds
var skipLive = true;        // If true, skip any albums whose grouping is "Live"


// useful 'map' method for arrays - I don't know why standard JS doesn't include this,
// considering it otherwise has such good functional support
Array.prototype.map = function(fnc) {
    var a = new Array(this.length);
    for (var i = 0; i < this.length; i++) {
        a[i] = fnc(this[i]);
    }
    return a;
}



// This is a list of songs that should be counted even if they are less than the minimum
// song length
var shortSongs = { "Smashing Pumpkins-Siamese Dream-Sweet Sweet": true,
                   "Sigur Rós-Takk...-Takk...": true,
                   "Neko Case-Fox Confessor Brings the Flood-At Last": true
                 };



// get the library reference
//var sources = MacOS.appByBundleID("com.apple.itunes").sources;


var library = MacOS.appBySignature("hook").sources[1].playlist["Library"];

//var library = sources["Library"].playlist["Library"];

var albums = {};
//var totalAlbumCount = library.

var totalTracks = library.tracks.length;

for (var i = 1; i <= totalTracks; i++) {
    var song = library.tracks[i];
    var albumName = song.album;
    if (albums[albumName] == null)
        albums[albumName] = {title: albumName, artist: song.artist, total:0, count:0, average:0, ratedCount: 0};
    
    // skip live songs, unchecked songs and those less the minimum song length
    if (song.enabled && !(skipLive && song.grouping=='Live') && (song.duration>minSongLength || shortSongs[song.artist + '-' + song.album + '-' + song.title])) {
        albums[albumName].count++;
        albums[albumName].total += song.rating;
        
        if (song.rating > 0)
            albums[albumName].ratedCount++;
    }
}

var sortedAlbums = new Array();
for (albumName in albums) {
    var album = albums[albumName];
    
    if (album.count > minTracks && (!onlyFullyRated || (album.count==album.ratedCount))) {
        album.average = Math.round(album.total / album.count);
        sortedAlbums.push(album);
    }
}

//Core.message("test message");

// sorts by average, then artist name
// wish we had perl's cmp operator for this
sortedAlbums.sort(function(a,b) {
    if (a.average != b.average) {
        return b.average-a.average;
    }
    else if (a.artist == b.artist) {
        return 0;
    }
    else if (a.artist > b.artist) {
        return 1;
    }
    else {
        return -1;
    }
});

// return the album listing in a nice, easy to read format
// Artist Name, "Album Name": Avg (TotalScore/NumberOfTracks)
// The Band, "The Band": 93 (1120/12)
sortedAlbums.map(function(a){ return a.artist + ', "' + a.title + '": ' + a.average + " (" + a.total + "/" + a.count + ")"; }).join("\r");