#include "usermodel.h"

UserModel::UserModel( QObject *parent ): QAbstractListModel( parent )
{

}

int UserModel::rowCount( const QModelIndex &parent ) const
{
    Q_UNUSED( parent );
    int count = userMap.values( current ).count();
    qDebug() << "count  of current channel users" << count;
    return count;
}

QVariant UserModel::data( const QModelIndex &index, int role ) const
{
    auto userList = userMap.values( current );

    if ( userList.count() < index.row() ) {
        return QVariant();
    }

    auto user = userList.at( index.row() );

    if ( role == UserRoles::UserName ) {
        return user->getUserName();
    };

    return QVariant();
}

bool UserModel::insertUser( QString channelId, QSharedPointer<RocketChatUser> user )
{

    if ( !user.isNull() && !duplicateCheck.contains( user->getUserId() ) ){


        auto values =  userMap.values( channelId );
        int index = values.count();

        if ( channelId == current ) {
            beginInsertRows( QModelIndex(), index, index );
        }

        userMap.insert( channelId, user );

        if ( channelId == current ) {
            endInsertRows();
            emit countChanged();
        }
    }else{
        return true;
    }
    //TODO: give some meainingfull return
    return true;
}

QString UserModel::getCurrent() const
{
    return current;
}

void UserModel::setCurrent( const QString &value )
{
    current = value;
}

void UserModel::onCurrentChannelChanged( const QString &newText )
{
    current = newText;
}

QHash<int, QByteArray> UserModel::roleNames() const
{
    QHash<int, QByteArray> roles;
    roles[UserName] = "username";
    roles[UserId] =  "userId";
    return roles;
}