/*
 *  eventid.cpp  -  KAlarm unique event identifier for resources
 *  Program:  kalarm
 *  Copyright © 2012-2020 David Jarvie <djarvie@kde.org>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */


#include "eventid.h"

#include "resources/resources.h"
#include "kalarm_debug.h"

#include <QRegularExpression>

/** Set by event ID prefixed by optional resource ID, in the format "[rid:]eid". */
EventId::EventId(const QString& resourceEventId)
{
    const QString resourceIdString = extractIDs(resourceEventId, mEventId);
    if (!resourceIdString.isEmpty())
        mResourceId = getResourceId(resourceIdString);  // convert the resource ID string
}

bool EventId::operator==(const EventId& other) const
{
    return mEventId == other.mEventId  &&  mResourceId == other.mResourceId;
}

ResourceId EventId::resourceDisplayId() const
{
    return (mResourceId > 0) ? (mResourceId & ~ResourceType::IdFlag) : mResourceId;
}

QString EventId::extractIDs(const QString& resourceEventId, QString& eventId)
{
    QRegularExpression rx(QStringLiteral("^(\\w+):(.*)$"));
    QRegularExpressionMatch rxmatch = rx.match(resourceEventId);
    if (!rxmatch.hasMatch())
    {
        eventId = resourceEventId;   // no resource ID supplied
        return QString();
    }

    // A resource ID has been supplied
    eventId = rxmatch.captured(2);
    return rxmatch.captured(1);
}

ResourceId EventId::getResourceId(const QString& resourceIdString)
{
    // Check if a resource configuration name has been supplied.
    Resource res = Resources::resourceForConfigName(resourceIdString);
    if (res.isValid())
        return res.id();

    // Check if a resource ID number has been supplied.
    bool ok;
    const ResourceId id = resourceIdString.toLongLong(&ok);
    if (ok)
    {
        res = Resources::resource(id);
        if (res.isValid())
            return id;
    }
    return -1;
}

// vim: et sw=4:
