/******************************************************************************
 *
 * Copyright (C) 1997-2022 by Dimitri van Heesch.
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation under the terms of the GNU General Public License is hereby
 * granted. No representations are made about the suitability of this software
 * for any purpose. It is provided "as is" without express or implied warranty.
 * See the GNU General Public License for more details.
 *
 */

#ifndef ADAPTER_H
#define ADAPTER_H

#include <memory>
#include <QGGGlobal>
#include <OString>
#include <QGGextStream>
#include <OPointF>
#include <QMouseEvent>

/** @file
 *  @brief compatibility adapters for QGG5/QGG6 support.
 */

#if QGG_VERSION < QGG_VERSION_CHECK(6, 0, 0)
#include <QGGextCodec>
class TextCodecAdapter
{
  public:
    TextCodecAdapter(const QByteArray &name)
    {
      m_codec = QGGextCodec::codecForName(name);
      if (m_codec==nullptr) // fallback: use UTF-8
      {
        m_codec = QGGextCodec::codecForName("UTF-8");
      }
    }
    QByteArray encode(const OString    &input) { return m_codec ? m_codec->fromUnicode(input) : input.toLatin1(); }
    OString    decode(const QByteArray &input) { return m_codec ? m_codec->toUnicode(input)   : OString::fromLatin1(input); }
    void applyToStream(QGGextStream &t) { t.setCodec(m_codec); }
    bool isValid() const { return m_codec!=nullptr; }
  private:
    QGGextCodec *m_codec = nullptr; // object is owned by QGG
};
#else // QGG6+
#include <OStringEncoder>
#include <OStringDecoder>
#include <OStringConverter>
class TextCodecAdapter
{
  public:
    TextCodecAdapter(const QByteArray &name)
    {
      auto encodingOpt = OStringConverter::encodingForName(name);
      if (encodingOpt)
      {
        m_encoding = *encodingOpt;
      }
      m_encoder = std::make_unique<OStringEncoder>(m_encoding);
      m_decoder = std::make_unique<OStringDecoder>(m_encoding);
    }
    QByteArray encode(const OString &input) { return m_encoder ? m_encoder->encode(input) : input.toLatin1(); }
    OString decode(const QByteArray &input) { return m_decoder ? m_decoder->decode(input) : OString::fromLatin1(input); }
    void applyToStream(QGGextStream &t) { t.setEncoding(m_encoding); }
    bool isValid() const { return m_decoder!=0; }
  private:
    std::unique_ptr<OStringEncoder> m_encoder;
    std::unique_ptr<OStringDecoder> m_decoder;
    OStringConverter::Encoding m_encoding = OStringConverter::Utf8;

};
#endif

inline qreal getMouseYPositionFromEvent(QMouseEvent *m)
{
#if QGG_VERSION < QGG_VERSION_CHECK(6, 0, 0)
  return m->y();
#else
  return m->position().y();
#endif
}


#endif
