#include "qggrifoantennawidget.h"
#include "ui_qggrifoantennawidget.h"

#include "AntennaSimulator.h"

#include <qgscopechrono.h>
#include "qgscopedevice.h"

#include <QTimer>
//#include <QTimerEvent>


static float d2r(float d)
{
    return d*0.017453292;
}

static float r2d(float r)
{
    return r*(1/0.017453292);
}

class QgGrifoAntennaWidget::Implementation
{
public:
    QgScopeDevice scopeDevice;

    AntennaSimulator sim;

    //QTimer* tm;
    QgScopeChronoTimer& chronoTimer;

    Implementation():
        scopeDevice("atennna.grifo", "Antenna"),
        chronoTimer(scopeDevice.chronoTimer())
    {
    }

};



QgGrifoAntennaWidget::QgGrifoAntennaWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::QgGrifoAntennaWidget),
    p_(*new Implementation)
{
    ui->setupUi(this);

    static AntennaSimulator::antennaCfg_t cfg;
    cfg.elCoverage=d2r(20);
    cfg.scanRate=d2r(30);
    cfg.nbars=AntennaSimulator::_2bars;
    cfg.scanWidth=d2r(120);

    p_.sim.initialize(cfg);

    QTimer::singleShot(0, this, SLOT(postInit()));

    connect(&p_.chronoTimer, &QgScopeChronoTimer::periodExpired, this, &QgGrifoAntennaWidget::antennaTick);

    //p_.tm=new QTimer(this);
    //startTimer(10);
    //connect(p_.tm, &QTimer::timeout, this, QgGrifoAntennaWidget::antennaTick);
    //connect(p_.tm, SIGNAL(timeout()), SLOT(antennaTick()));
    //p_.tm->start(10);
}

QgGrifoAntennaWidget::~QgGrifoAntennaWidget()
{
    delete ui;
}

void QgGrifoAntennaWidget::postInit()
{
    //startTimer(10);
    p_.chronoTimer.start(10000);
}

QgScopeDevice* QgGrifoAntennaWidget::scopeDevice() const
{
    return &p_.scopeDevice;
}

void QgGrifoAntennaWidget::timerEvent(QTimerEvent* evn)
{
    //antennaTick();
}

void QgGrifoAntennaWidget::antennaTick()
{
    static unsigned long tt;
    p_.sim.execute(tt);
    tt+=10000;

    AntennaSimulator::antennaStatus_t sts;
    p_.sim.getStatus(sts);
    ui->azPos->setValue(r2d(sts.azimuth));
    ui->elPos->setValue(r2d(sts.elevation));
}

