#include <QtCore/QCoreApplication>
#include <QDateTime>
#include "musiclibrarybuilder.h"

// Passed to qSort to sort records by release date
static bool sortByDate(const Record *obj1, const Record *obj2)
{
    return obj1->releaseDate() < obj2->releaseDate();
}

// Passed to qSort to sort songs by song number
static bool sortByNumber(const Song *obj1, const Song *obj2)
{
    return obj1->number() < obj2->number();
}

// Passed to qSort to sort objects by name
static bool sortByName(const MusicObject *obj1, const MusicObject *obj2)
{
    return obj1->name() < obj2->name();
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // Use builder library to add contents
    MusicLibrary *lib = MusicLibraryBuilder::build();

    qDebug("Tree (artists alphabetically, records by date, songs by number):");

    // Get artists and sort them by name
    // For each artist, get records and sort by release date
    // For each record, get songs and sort by song number
    QList<Artist *> artists = lib->artists();
    qSort(artists.begin(), artists.end(), sortByName);
    foreach (Artist *artist, artists) {
        qDebug("  %s (%s)", artist->name().toAscii().data(),
               qPrintable(artist->homePage().toString()));
        QList<Record *> records = artist->records();
        qSort(records.begin(), records.end(), sortByDate);
        foreach (Record *record, records) {
            qDebug("    %s (%s)", record->name().toAscii().data(),
                   qPrintable(record->releaseDate().toString("ddd MMM d yyyy")));
            QList<Song *> songs = record->songs();
            qSort(songs.begin(), songs.end(), sortByNumber);
            foreach (Song *song, songs) {
                qDebug("      %d %s", song->number(), qPrintable(song->name()));
            }
        }
    }

    qDebug("Artists alphabetically:");
    artists = lib->artists();
    qSort(artists.begin(), artists.end(), sortByName);
    foreach (Artist *artist, artists) {
        qDebug("  %s (%s)", qPrintable(artist->name()),
               qPrintable(artist->homePage().toString()));
    }

    qDebug("Records alphabetically:");
    QList<Record *> records = lib->records();
    qSort(records.begin(), records.end(), sortByName);
    foreach (Record *record, records) {
        qDebug("  %s (%s)", qPrintable(record->name()),
               qPrintable(record->releaseDate().toString("ddd MMM d yyyy")));
    }

    qDebug("Songs alphabetically:");
    QList<Song *> songs = lib->songs();
    qSort(songs.begin(), songs.end(), sortByName);
    foreach (Song *song, songs) {
        qDebug("  %s (%s, %d)", qPrintable(song->name()),
               qPrintable(song->record()->name()), song->number());
    }

    delete lib;
    MusicLibrary::dumpMemory();

    return 0;
}
