/***************************************************************************
**
**  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: 2011-08-11
**  Copyright: 2011-2019
**    Marc Wathelet (ISTerre, Grenoble, France)
**
***************************************************************************/

#include <QtQml>

#include "SignalHeaderObject.h"
#include "SignalHeaderScript.h"
#include "Comments.h"

namespace GeopsyCore {

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

    Full description of class still missing
  */

  /*!
    Description of constructor still missing
  */
  SignalHeaderScript::SignalHeaderScript(SubSignalPool * subPool)
  {
    TRACE;
    _engine=new QJSEngine(this);
    ScriptContext::add(_engine);
    //_signalHeader=new SignalHeaderPrototype(this);
    //_engine->setDefaultPrototype(qMetaTypeId<GeopsyCore::Signal *>(),
    //                             _engine->newQObject(_signalHeader));
    //connect(_signalHeader, SIGNAL(dataChanged(Signal*)), this, SIGNAL(dataChanged(Signal *)));
    //MetaDataFactory::instance()->registerScriptTypes(_engine);


    int n=subPool->count();
    QJSValue list, sig;
    list=_engine->newArray(n);
    _engine->globalObject().setProperty("signals", list);
    for(int i=0; i<n; i++) {
      SignalHeaderObject * obj=new SignalHeaderObject(subPool->at(i), this);
      connect(obj, SIGNAL(beginSignalChange(Signal*)), this, SIGNAL(beginSignalChange(Signal*)));
      connect(obj, SIGNAL(endSignalChange(Signal*)), this, SIGNAL(endSignalChange(Signal*)));
      sig=_engine->newQObject(obj);
      list.setProperty(i, sig);
    }
  }

  bool SignalHeaderScript::run(const QString& script)
  {
    TRACE;
    QJSValue ret=_engine->evaluate(script);
    if(ret.isError()) {
      App::log(tr("Uncaught exception at line %1:\n %2\n")
                       .arg(ret.property("lineNumber").toInt())
                       .arg(ret.toString()));
      return false;
    } else {
      return true;
    }
  }

} // namespace GeopsyCore
