/***************************************************************************
**
**  This file is part of GeopsyCore.
**
**  GeopsyCore 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.
**
**  GeopsyCore 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 Foobar.  If not, see <http://www.gnu.org/licenses/>
**
**  See http://www.geopsy.org for more information.
**
**  Created: 2016-12-01
**  Copyright: 2016-2019
**    Marc Wathelet (ISTerre, Grenoble, France)
**
***************************************************************************/

#ifndef FFTWCACHE_H
#define FFTWCACHE_H

#include <QGpCoreMath.h>
#include <fftw3.h>

#include "DoubleSignal.h"
#include "GeopsyCoreDLLExport.h"

namespace GeopsyCore {

  class GEOPSYCORE_EXPORT FFTWKey : public AbstractNumericalKey
  {
    DECLARE_NUMERICALKEY(FFTWKey)
  public:
    enum Direction{R2HC=1, HC2R=2};

    FFTWKey(int nSamples, Direction direction) {
      _nSamples=nSamples;
      _direction=direction;
    }

    virtual bool operator==(const AbstractNumericalKey& o) {
      const FFTWKey& fo=static_cast<const FFTWKey&>(o);
      return _nSamples==fo._nSamples;
    }
    virtual int hash() const {return 2*_nSamples+(_direction-1);}
    inline virtual AbstractNumericalCache * createCache();

    int nSamples() const {return _nSamples;}
    Direction direction() const {return _direction;}
  private:
    Thread * _thread;
    int _nSamples;
    Direction _direction;
  };

  class GEOPSYCORE_EXPORT FFTWCache : public AbstractNumericalCache
  {
  public:
    FFTWCache(FFTWKey * key);
    ~FFTWCache();

    static inline const FFTWCache * begin(int nSamples, FFTWKey::Direction direction);
    virtual void init();
    virtual bool inherits(const char * className);

    void execute(double * samples) const;
  private:
    mutable DoubleSignal _fft;
    fftw_plan _plan;
    static Mutex _plannerMutex;
  };

  inline const FFTWCache * FFTWCache::begin(int nSamples, FFTWKey::Direction direction)
  {
    return static_cast<const FFTWCache *>(
        AbstractNumericalCache::begin(new FFTWKey(nSamples, direction)));
  }

  inline AbstractNumericalCache * FFTWKey::createCache()
  {
    return new FFTWCache(this);
  }

} // namespace GeopsyCore

#endif // FFTWCACHE_H

