/* Copyright (C) 2004-2014 MBSim Development Team
 *
 * This library is free software; you can redistribute it and/or 
 * modify it under the terms of the GNU Lesser General Public 
 * License as published by the Free Software Foundation; either 
 * version 2.1 of the License, or (at your option) any later version. 
 *  
 * This library 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 
 * Lesser General Public License for more details. 
 *  
 * You should have received a copy of the GNU Lesser General Public 
 * License along with this library; if not, write to the Free Software 
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
 *
 * Contact: martin.o.foerg@gmail.com
 */

#ifndef _SINUSOIDAL_FUNCTION_H_
#define _SINUSOIDAL_FUNCTION_H_

#include "mbsim/functions/function.h"
#include "mbsim/utils/utils.h"

namespace MBSim {

  template<typename Sig> class SinusoidalFunction; 

  template<typename Ret, typename Arg>
  class SinusoidalFunction<Ret(Arg)> : public Function<Ret(Arg)> {
    using B = fmatvec::Function<Ret(Arg)>; 
    protected:
      double A, f, phi0, y0;
    public:
      SinusoidalFunction(double A_=0, double f_=0, double phi0_=0, double y0_=0) : A(A_), f(f_), phi0(phi0_), y0(y0_) { }
      void setAmplitude(double A_) { A = A_; }
      void setFrequency(double f_) { f = f_; }
      void setPhase(double phi0_) { phi0 = phi0_; }
      void setOffset(double y0_) { y0 = y0_; }
      int getArgSize() const override { return 1; }
      std::pair<int, int> getRetSize() const override { return std::make_pair(1,1); }
      Ret operator()(const Arg &x) override {  
        return FromDouble<Ret>::cast(y0+A*sin(2.*M_PI*f*ToDouble<Arg>::cast(x)+phi0));
      }
      typename B::DRetDArg parDer(const Arg &x) override {  
        double om = 2.*M_PI*f;
        return FromDouble<typename B::DRetDArg>::cast(A*om*cos(om*ToDouble<Arg>::cast(x)+phi0));
      }
      typename B::DRetDArg parDerDirDer(const Arg &xDir, const Arg &x) override { 
        double om = 2.*M_PI*f;
        return FromDouble<typename B::DRetDArg>::cast(-A*om*om*sin(om*ToDouble<Arg>::cast(x)+phi0)*ToDouble<Arg>::cast(xDir));
      }
      void initializeUsingXML(xercesc::DOMElement *element) override {
        xercesc::DOMElement *e=MBXMLUtils::E(element)->getFirstElementChildNamed(MBSIM%"amplitude");
        setAmplitude(MBXMLUtils::E(e)->getText<double>());
        e=MBXMLUtils::E(element)->getFirstElementChildNamed(MBSIM%"frequency");
        setFrequency(MBXMLUtils::E(e)->getText<double>());
        e=MBXMLUtils::E(element)->getFirstElementChildNamed(MBSIM%"phase");
        if(e) setPhase(MBXMLUtils::E(e)->getText<double>());
        e=MBXMLUtils::E(element)->getFirstElementChildNamed(MBSIM%"offset");
        if(e) setOffset(MBXMLUtils::E(e)->getText<double>());
      }
  };

}

#endif
