/***************************************************************************

    source::worx xtree
    Copyright © 2024-2025 c.holzheuer
    christoph.holzheuer@gmail.com

    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.

***************************************************************************/


#ifndef XQPTRMAPTOR_H
#define XQPTRMAPTOR_H

#include <xqmaptor.h>

/**
 * @brief A XQMaptor implementation for pointers to to data entries.
 */

template<typename T>
class  XQPtrMaptor : public XQMaptor<T*>
{

public:

  virtual ~XQPtrMaptor()
  {
    for (int i = 0; i < this->_data.size(); ++i)
      delete this->_data[i];
  }

  T& entry(const QString& key)
  {
    int i = this->indexOf(key);
    if (i < 0)
      throw  XQException("XQPtrMaptor: entry: not found: " + key);
    return *(this->_data[i]);
  }

  const T& entry(const QString& key) const
  {
    int i = this->indexOf(key);
    if (i < 0)
      throw  XQException("XQPtrMaptor: entry: not found: " + key);
    return *(this->_data[i]);
  }

  T& entry(int index)
  {
    if ((int)index < this->_data.size())
      return *(this->_data[index]);
    throw XQException("ddmapptr entry( int index ): out of range");
  }


  const T& entry(int index) const
  {
    if (index > 0 && index < this->_data.size())
      return *(this->_data[index]);
    throw XQException("ddmapptr const entry( int index ): out of range");
  }


  bool killEntry(const QString& key) override
  {
    int idx = this->indexOf(key);
    // warum keine exception?
    if (idx < 0)
      return false;
    return killEntry((int)idx);
  }

  bool killEntry(int index) override
  {
    T* item = this->_data[index];
    if (XQMaptor<T*>::killEntry(index))
    {
      delete item;
      return true;
    }
    return false;
  }


  bool removeEntry(const QString& key)
  {
    int idx = this->indexOf(key);
    // warum keine exception?
    if (idx < 0)
      return false;
    return removeEntry((int)idx);
  }


  bool removeEntry(int index)
  {
    if (index >= this->_data.size())
      return false;

    // eintrag löschen
    this->_data.erase(this->_data.begin() + index);
    // index updaten
    this->_index.update(index);

    return true;
  }


  void replace(int index, T* entry)
  {
    if ((int)index >= this->_data.size())
      throw XQException("ddmapptr replace( int index ): out of range");
    delete(this->_data[index]);
    this->_data[index] = entry;
  }

  void replace(const QString& key, T* entry)
  {
    replace(this->indexOf(key), entry);
  }

};
ö
#endif // XQPTRMAPTOR_H
