#include "musiclibrarylistprivate.h"
#include "musiclibrary.h"
#include "artist.h"
#include "record.h"
#include "song.h"

MusicLibraryListPrivate::MusicLibraryListPrivate(MusicLibrary *l, ModelType t) : library(l), type(t)
{
    switch (type) {
    case Artists:
        {
            QList<Artist *> artists = library->artists();
            foreach (Artist *a, artists) {
                modelData.append(a);
            }
        }
        break;
    case Records:
        {
            QList<Record *> records = library->records();
            foreach (Record *r, records) {
                modelData.append(r);
            }
        }
        break;
    case Songs:
        {
            QList<Song *> songs = library->songs();
            foreach (Song *s, songs) {
                modelData.append(s);
            }
        }
        break;
    }
    connect(library, SIGNAL(objectChanged(MusicObject*)), SLOT(objectChanged(MusicObject*)));
}

int MusicLibraryListPrivate::rowCount(const QModelIndex &parent) const
{
    // Only the root (invalid model index) may contain elements, since this is a list
    if (parent.isValid()) {
        return 0;
    }

    return modelData.count();
}

QVariant MusicLibraryListPrivate::data(const QModelIndex &index, int role) const
{
    // Only column 0 may contain data, since this is a single-column list
    if (index.column() != 0) {
        return QVariant();
    }

    // Only display role is supported in this simple example
    if (role != Qt::DisplayRole && role != Qt::UserRole) {
        return QVariant();
    }

    // Check that row is within bounds
    int row = index.row();
    if (row < 0 || row >= modelData.count()) {
        return QVariant();
    }

    // Return the object with user role and name as display role
    if (role == Qt::UserRole) {
        return qVariantFromValue<QObject *>(modelData[row]);
    } else {
        return modelData[row]->name();
    }
}

void MusicLibraryListPrivate::objectChanged(MusicObject *obj)
{
    // Index of the object needs to be looked up from array
    int listIndex = modelData.indexOf(obj);
    if (listIndex >= 0) {
        // If found, a dataChanged notification is made, so views can update themselves
        QModelIndex modelIndex = index(listIndex);
        emit dataChanged(modelIndex, modelIndex);
    }
}
