/***************************************************************************
**
**  This file is part of SciFigs.
**
**  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 file 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
**
**  See http://www.geopsy.org for more information.
**
**  Created: 2018-10-18
**  Copyright: 2018-2019
**    Marc Wathelet (ISTerre, Grenoble, France)
**
***************************************************************************/

#include "LiveCurveLayer.h"
#include "LayerLocker.h"
#include "AxisWindow.h"
#include "AutoAdjustScale.h"
#include "AutoAdjustScaleProperties.h"
#include "GraphContent.h"
#include "PlotLine2D.h"
#include "LayerPainterRequest.h"
#include "XMLSciFigs.h"

namespace SciFigs {

  /*!
    \class LiveCurveLayer LiveCurveLayer.h
    \brief Brief description of class still missing

    Full description of class still missing
  */

  /*!
    Description of constructor still missing
  */
  LiveCurveLayer::LiveCurveLayer(AxisWindow * parent)
    : LineLayer(parent)
  {
    TRACE;
    _function=nullptr;
    _sampling=1;
    _variables=X;
    _min=0.0;
    _max=0.0;
    PlotLine2D * line=new PlotLine2D;
    line->setPen(Pen(Qt::black, 0.3, Qt::SolidLine));
    line->setSymbol(Symbol());
    setReferenceLine(line);

    // Adjusting of scale cannot be done inside the paint event (multi-threaded)
    connect(this, SIGNAL(scaleChanged(double, double, Axis *)),
            this, SLOT(adjustScale(double, double, Axis *)), Qt::QueuedConnection);
  }

  /*!
    Description of destructor still missing
  */
  LiveCurveLayer::~LiveCurveLayer()
  {
    TRACE;
    delete _function;
  }

  void LiveCurveLayer::setFunction(AbstractFunction * f)
  {
    TRACE;
    LayerLocker ll(this);
    delete _function;
    _function=f;
  }

  AbstractFunction * LiveCurveLayer::takeFunction()
  {
    TRACE;
    LayerLocker ll(this);
    AbstractFunction * f=_function;
    _function=nullptr;
    return f;
  }

  void LiveCurveLayer::adjustScale(double min, double max, Axis * a) const
  {
    TRACE;
    if(forceMinimumValue()) {
      min=minimumValue();
    }
    if(forceMaximumValue()) {
      max=maximumValue();
    }
    if(forceRatio()) {
      min=max/ratio();
    }
    a->setRange(min, max);
    switch(scale()) {
    case SamplingParameters::Linear:
      a->setScaleType(Scale::Linear);
      break;
    case SamplingParameters::Log:
      a->setScaleType(Scale::Log);
      break;
    }
  }

  uint LiveCurveLayer::_tab=PropertyProxy::uniqueId();

  /*!
    Setup property editor
  */
  void LiveCurveLayer::addProperties(PropertyProxy * pp)
  {
    TRACE;
    LineLayer::addProperties(pp);
    /*if(pp->setCurrentTab(_tab)) {
      pp->addReference(this);
    } else {
      AutoAdjustScaleProperties * w=new AutoAdjustScaleProperties;
      pp->addTab(_tab, tr("Axis update"), w, this);
    }*/
  }

  /*!
    Clean property editor
  */
  void LiveCurveLayer::removeProperties(PropertyProxy * pp)
  {
    TRACE;
    //pp->removeTab(_tab, this);
    LineLayer::removeProperties(pp);
  }

  void LiveCurveLayer::properties(PropertyWidget * w) const
  {
    TRACE;
    if(w->id()==_tab) {
      //AutoAdjustScale::properties(w);
    } else {
      LineLayer::properties(w);
    }
  }

  void LiveCurveLayer::setProperty(uint wid, int pid, QVariant val)
  {
    TRACE;
    if(wid==_tab) {
      //AutoAdjustScale::setProperties(pid, val);
    } else {
      LineLayer::setProperty(wid, pid, val);
    }
  }

  Rect LiveCurveLayer::boundingRect() const
  {
    TRACE;
    return Rect();
  }

  void LiveCurveLayer::paintData(const LayerPainterRequest& lp, QPainter& p, double dotpercm) const
  {
    TRACE;
    const GraphContentOptions& gc=lp.options();
    if(!_function) {
      return;
    }
    PlotLine2D line=*static_cast<PlotLine2D *>(_referenceLine);
    line.setCurve(calculateCurve(lp.size(), lp.options(), &lp));

    if(autoAdjust() && !line.curve().isEmpty()) {
      double min=line.curve().at(line.curve().minimumY()).y();
      double max=line.curve().at(line.curve().maximumY()).y();
      if(std::isnormal(min) &&
         std::isnormal(max) &&
         (min!=_min || max !=_max)) {
        _min=min;
        _max=max;
        emit scaleChanged(0.9*_min, 1.1*_max, graph()->yAxis());
      }
    }

    int h=lp.size().height();
    Rect r(gc.xVisMin(), gc.yVisMin(), gc.xVisMax(), gc.yVisMax());
    drawCurve(gc, p, dotpercm, h, r, line, 0, line.count());
  }

  Curve<Point2D> LiveCurveLayer::calculateCurve(const QSize& s, const GraphContentOptions& gc,
                                                const LayerPainterRequest * lp) const
  {
    TRACE;
    int nx=s.width()/_sampling;
    Curve<Point2D> curve(nx);

    double x,y;
    SAFE_UNINITIALIZED(y, 0.0)
    int iStart=_sampling >> 1;
    int ixGrid0, ixGrid, dixGrid, ixEndGrid;
    if(graph()->xAxis()->isEffectivelyReversed()) {
      ixGrid0=nx-1;
      dixGrid=-1;
      ixEndGrid=-1;
    } else {
      ixGrid0=0;
      dixGrid=1;
      ixEndGrid=nx;
    }
    ixGrid=ixGrid0;
    if(lp) {
      lp->graphContent()->setProgressMaximum(s.width());
    }
    for(int ix=iStart; ixGrid!=ixEndGrid; ix+=_sampling, ixGrid+=dixGrid) {
      if(lp && lp->terminated()) {
        return curve;
      }
      x=gc.xs2r(ix);
      switch(_variables) {
      case X:
        y=_function->value(Point(x, 0.0, 0.0));
        break;
      case Y:
        y=_function->value(Point(0.0, x, 0.0));
        break;
      case Z:
        y=_function->value(Point(0.0, 0.0, x));
        break;
      }
      curve[ixGrid]=Point2D(x, y);
    }
    if(lp) {
      lp->graphContent()->setProgressValue(s.height());
    }
    return curve;
  }

  void LiveCurveLayer::xml_writeChildren(XML_WRITECHILDREN_ARGS) const
  {
    TRACE;
    if(!_function) {
      return;
    }
    // Calculate curve with current plot limits
    PlotLine2D line=*static_cast<PlotLine2D *>(_referenceLine);
    line.setCurve(calculateCurve(graphContent()->size(), graphContent()->options()));

    static const QString key("index");
    XMLSaveAttributes att;
    QString& value=att.add(key);
    if(_referenceLine) {
      value="reference";
      _referenceLine->xml_save(s, context, att);
    }
    value="0";
    line.xml_save(s, context, att);
  }

} // namespace SciFigs

