/*
 * Copyright (C) 2014-2024 CZ.NIC
 *
 * 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 3 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, see <http://www.gnu.org/licenses/>.
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations including
 * the two.
 */

#include "src/datovka_shared/identifiers/account_id.h"
#include "src/models/account_unique_numid.h"

/* Null objects - for convenience. */
static const AcntId nullAcntId;

AcntNumId::AcntNumId(void)
    : m_num2acntId(),
    m_acntId2num()
{
}

void AcntNumId::clear(void)
{
	m_num2acntId.clear();
	m_acntId2num.clear();
}

int AcntNumId::addAcntId(const AcntId &acntId)
{
	if (Q_UNLIKELY(m_acntId2num.contains(acntId))) {
		Q_ASSERT(0);
		return -1;
	}

	int num = m_num2acntId.size();
	m_num2acntId.append(acntId);
	m_acntId2num[acntId] = num;
	return num;
}

void AcntNumId::removeAcntId(const AcntId &acntId)
{
	if (Q_UNLIKELY(!m_acntId2num.contains(acntId))) {
		Q_ASSERT(0);
		return;
	}

	int num = m_acntId2num[acntId];
	m_num2acntId[num] = AcntId();
	m_acntId2num.remove(acntId);
}

int AcntNumId::replaceAcntId(const AcntId &oldId, const AcntId &newId)
{
	if (Q_UNLIKELY(!m_acntId2num.contains(oldId))) {
		Q_ASSERT(0);
		return -1;
	}

	int num = m_acntId2num[oldId];
	m_num2acntId[num] = newId;
	m_acntId2num.remove(oldId);
	m_acntId2num[newId] = num;
	return num;
}

const AcntId &AcntNumId::acntId(int numId) const
{
	if (Q_UNLIKELY(numId >= m_num2acntId.size())) {
		Q_ASSERT(0);
		return nullAcntId;
	}

	return m_num2acntId.at(numId);
}

int AcntNumId::numId(const AcntId &acntId) const
{
	QMap<AcntId, int>::const_iterator it = m_acntId2num.constFind(acntId);
	if (Q_UNLIKELY(it == m_acntId2num.constEnd())) {
		Q_ASSERT(0);
		return -1;
	}

	return it.value();
}
