#pragma once
#include "call_once.h"
#include <QScopedPointer>
#include <QtGlobal>

// from https://stackoverflow.com/questions/46172607/qt-singleton-implementation

template <class T> class GenericSingelton {
private:
  typedef T *(*CreateInstanceFunction)();

public:
  static T *instance(CreateInstanceFunction create);

private:
  static void init();

  GenericSingelton();
  ~GenericSingelton();
  Q_DISABLE_COPY(GenericSingelton)
  static QBasicAtomicPointer<void> create;
  static QBasicAtomicInt flag;
  static QBasicAtomicPointer<void> tptr;
  bool inited;
};

template <class T>
T *GenericSingelton<T>::instance(CreateInstanceFunction create) {
  GenericSingelton::create.store(reinterpret_cast<void *>(create));
  qCallOnce(init, flag);
  return (T *)tptr.load();
}

template <class T> void GenericSingelton<T>::init() {
  static GenericSingelton singleton;
  if (singleton.inited) {
    CreateInstanceFunction createFunction =
        (CreateInstanceFunction)GenericSingelton::create.load();
    tptr.store(createFunction());
  }
}

template <class T> GenericSingelton<T>::GenericSingelton() { inited = true; }

template <class T> GenericSingelton<T>::~GenericSingelton() {
  T *createdTptr = (T *)tptr.fetchAndStoreOrdered(nullptr);
  if (createdTptr) {
    delete createdTptr;
  }
  create.store(nullptr);
}

template <class T>
QBasicAtomicPointer<void>
    GenericSingelton<T>::create = Q_BASIC_ATOMIC_INITIALIZER(nullptr);
template <class T>
QBasicAtomicInt GenericSingelton<T>::flag =
    Q_BASIC_ATOMIC_INITIALIZER(CallOnce::CO_Request);
template <class T>
QBasicAtomicPointer<void>
    GenericSingelton<T>::tptr = Q_BASIC_ATOMIC_INITIALIZER(nullptr);
