#include "grifodisplaywidget.h"

//#include "ui_grifodisplaywidget.h"


#include <functional>

#include "QGraphicImage256.h"

#include "qgvideorecorder.h"

#include <QMessageBox>
#include <QDateTime>

#include <QDebug>
#include <QToolButton>
#include <QLabel>
#include <QElapsedTimer>
#include <QComboBox>
#include <QMenu>
#include <QStyle>
#include <QApplication>

//#include <QThread>

#define X_DIM   640 //512
#define Y_DIM   512 //X_DIM

//UI
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QFrame>
#include <QtWidgets/QGraphicsView>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QToolButton>
#include <QtWidgets/QVBoxLayout>

class Ui_GrifoDisplayWidget
{
public:
    QAction *actionShowReferencePoint;
    QAction *actionShowNearestSymInfo;
    QAction *actionShowLockOnDes;
    QAction *actionMiniZoom;
    QAction *actionZoomIn;
    QAction *actionZoomOut;

    QAction* actionDbgShowAll;
    QAction* actionShowAntennaCaret;
    QAction* actionShowAntennaPath;
    QAction* actionHideTgtAlt;
    QAction* actionShowModeInfo;

    QVBoxLayout *verticalLayout;
    QHBoxLayout *horizontalLayout_2;
    QToolButton *localOcclusion;
    QToolButton *localFreeze;
    QToolButton *imageSnapshot;
    QToolButton *vcr;

    QComboBox *zoom;
    QFrame *line;
    QToolButton *dbgCrs;
    QToolButton *rdrCrs;
    QToolButton *dbgActions;
    QSpacerItem *horizontalSpacer;
    QLabel *lblPos;
    QLabel *labelInfo;
    QGraphicsView *rdrView;

    void setupUi(QFrame *pGrifoDisplayWidget)
    {
        if (pGrifoDisplayWidget->objectName().isEmpty())
            pGrifoDisplayWidget->setObjectName(QStringLiteral("GrifoDisplayWidget"));
        pGrifoDisplayWidget->resize(400, 300);
        pGrifoDisplayWidget->setFrameShape(QFrame::StyledPanel);
        pGrifoDisplayWidget->setFrameShadow(QFrame::Raised);
        actionShowReferencePoint = new QAction(pGrifoDisplayWidget);
        actionShowReferencePoint->setObjectName(QStringLiteral("actionShowReferencePoint"));
        actionShowReferencePoint->setCheckable(true);
        actionShowNearestSymInfo = new QAction(pGrifoDisplayWidget);
        actionShowNearestSymInfo->setObjectName(QStringLiteral("actionShowNearestSymInfo"));
        actionShowNearestSymInfo->setCheckable(true);
        actionShowLockOnDes = new QAction(pGrifoDisplayWidget);
        actionShowLockOnDes->setObjectName(QStringLiteral("actionShowLockOnDes"));
        actionShowLockOnDes->setCheckable(true);
        actionMiniZoom = new QAction(pGrifoDisplayWidget);
        actionMiniZoom->setObjectName(QStringLiteral("actionMiniZoom"));
        actionMiniZoom->setCheckable(true);
        actionZoomIn = new QAction(pGrifoDisplayWidget);
        actionZoomIn->setObjectName(QStringLiteral("actionZoomIn"));
        actionZoomOut = new QAction(pGrifoDisplayWidget);
        actionZoomOut->setObjectName(QStringLiteral("actionZoomOut"));

        actionDbgShowAll =new QAction(pGrifoDisplayWidget);
        actionDbgShowAll->setText("Show Debug");
        actionDbgShowAll->setObjectName(QStringLiteral("actionDbgShowAll"));
        actionDbgShowAll->setCheckable(true);
        actionDbgShowAll->setData(GrifoDisplayWidget::DbgSymFlagEna);

        actionShowAntennaCaret = new QAction(pGrifoDisplayWidget);
        actionShowAntennaCaret->setText("Shadow Caret");
        actionShowAntennaCaret->setObjectName(QStringLiteral("actionShowAntennaCaret"));
        actionShowAntennaCaret->setCheckable(true);
        actionShowAntennaCaret->setData(GrifoDisplayWidget::DbgSymFlagAntennaCaret);

        actionShowAntennaPath = new QAction(pGrifoDisplayWidget);
        actionShowAntennaPath->setText("Ant Path");
        actionShowAntennaPath->setObjectName(QStringLiteral("actionShowAntennaPath"));
        actionShowAntennaPath->setCheckable(true);
        actionShowAntennaPath->setData(GrifoDisplayWidget::DbgSymFlagAntennaPath);

        actionHideTgtAlt = new QAction(pGrifoDisplayWidget);
        actionHideTgtAlt->setText("Hide Tgt Alt");
        actionHideTgtAlt->setObjectName(QStringLiteral("actionHideTgtAlt"));
        actionHideTgtAlt->setCheckable(true);
        actionHideTgtAlt->setData(GrifoDisplayWidget::DbgSymTgtAltitude);

        actionShowModeInfo = new QAction(pGrifoDisplayWidget);
        actionShowModeInfo->setText("Mode Info");
        actionShowModeInfo->setObjectName(QStringLiteral("actionShowModeInfo"));
        actionShowModeInfo->setCheckable(true);
        actionShowModeInfo->setData(GrifoDisplayWidget::DbgSymShowModeInfo);

        verticalLayout = new QVBoxLayout(pGrifoDisplayWidget);
        verticalLayout->setSpacing(3);
        verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
        verticalLayout->setContentsMargins(3, 3, 3, 3);
        horizontalLayout_2 = new QHBoxLayout();
        horizontalLayout_2->setSpacing(3);
        horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2"));
        localOcclusion = new QToolButton(pGrifoDisplayWidget);
        localOcclusion->setObjectName(QStringLiteral("localOcclusion"));
        //QIcon icon;
        //icon.addFile(QStringLiteral(":/icons/icons/photo212.png"), QSize(), QIcon::Normal, QIcon::Off);
        //localOcclusion->setIcon(icon);
        localOcclusion->setCheckable(true);

        horizontalLayout_2->addWidget(localOcclusion);

        localFreeze = new QToolButton(pGrifoDisplayWidget);
        localFreeze->setObjectName(QStringLiteral("localFreeze"));

        imageSnapshot=new QToolButton(pGrifoDisplayWidget);
        imageSnapshot->setObjectName(QStringLiteral("imageSnapshot"));

        //QIcon icon1;
        //icon1.addFile(QStringLiteral(":/icons/icons/pause44.png"), QSize(), QIcon::Normal, QIcon::Off);
        //localFreeze->setIcon(icon1);
        localFreeze->setCheckable(true);

        horizontalLayout_2->addWidget(localFreeze);
        horizontalLayout_2->addWidget(imageSnapshot);

        zoom = new QComboBox(pGrifoDisplayWidget);
        zoom->setObjectName(QStringLiteral("zoom"));

        horizontalLayout_2->addWidget(zoom);

        line = new QFrame(pGrifoDisplayWidget);
        line->setObjectName(QStringLiteral("line"));
        line->setFrameShape(QFrame::VLine);
        line->setFrameShadow(QFrame::Sunken);

        horizontalLayout_2->addWidget(line);

        dbgCrs = new QToolButton(pGrifoDisplayWidget);
        dbgCrs->setObjectName(QStringLiteral("dbgCrs"));
        dbgCrs->setCheckable(true);

        horizontalLayout_2->addWidget(dbgCrs);

        rdrCrs = new QToolButton(pGrifoDisplayWidget);
        rdrCrs->setObjectName(QStringLiteral("rdrCrs"));
        rdrCrs->setCheckable(true);

        horizontalLayout_2->addWidget(rdrCrs);

        dbgActions = new QToolButton(pGrifoDisplayWidget);
        dbgActions->setObjectName(QStringLiteral("dbgActions"));
        //QIcon icon2;
        //icon2.addFile(QStringLiteral(":/icons/icons/list89.png"), QSize(), QIcon::Normal, QIcon::Off);
        //dbgActions->setIcon(icon2);
        dbgActions->setPopupMode(QToolButton::InstantPopup);

        horizontalLayout_2->addWidget(dbgActions);

        vcr=new QToolButton(pGrifoDisplayWidget);
        vcr->setObjectName("VideoVCR");
        vcr->setText("VCR");
        vcr->setCheckable(true);

        horizontalLayout_2->addWidget(vcr);

        horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);

        horizontalLayout_2->addItem(horizontalSpacer);

        lblPos = new QLabel(pGrifoDisplayWidget);
        lblPos->setObjectName(QStringLiteral("lblPos"));

        horizontalLayout_2->addWidget(lblPos);

        labelInfo = new QLabel(pGrifoDisplayWidget);
        labelInfo->setObjectName(QStringLiteral("labelInfo"));

        horizontalLayout_2->addWidget(labelInfo);


        verticalLayout->addLayout(horizontalLayout_2);

        rdrView = new QGraphicsView(pGrifoDisplayWidget);
        rdrView->setObjectName(QStringLiteral("rdrView"));

        verticalLayout->addWidget(rdrView);


        retranslateUi(pGrifoDisplayWidget);
        //QMetaObject::connectSlotsByName(pGrifoDisplayWidget);
    } // setupUi

    void retranslateUi(QFrame *GrifoDisplayWidget)
    {
#if 1
        GrifoDisplayWidget->setWindowTitle("Grifo Display"); //QApplication::translate("GrifoDisplayWidget", "Frame", Q_NULLPTR));
        actionShowReferencePoint->setText(QApplication::translate("GrifoDisplayWidget", "Show reference point", Q_NULLPTR));
        actionShowNearestSymInfo->setText(QApplication::translate("GrifoDisplayWidget", "ShowNearestSymInfo", Q_NULLPTR));
        actionShowLockOnDes->setText(QApplication::translate("GrifoDisplayWidget", "ShowLockOnDes", Q_NULLPTR));
        actionMiniZoom->setText(QApplication::translate("GrifoDisplayWidget", "MiniZoom", Q_NULLPTR));
        actionZoomIn->setText(QApplication::translate("GrifoDisplayWidget", "Zoom in", Q_NULLPTR));
        actionZoomOut->setText(QApplication::translate("GrifoDisplayWidget", "Zoom Out", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
        localOcclusion->setToolTip(QApplication::translate("GrifoDisplayWidget", "Show keycolor", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
        localOcclusion->setText(QApplication::translate("GrifoDisplayWidget", "Occlusion", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
        localFreeze->setToolTip(QApplication::translate("GrifoDisplayWidget", "Freeze", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
        localFreeze->setText(QApplication::translate("GrifoDisplayWidget", "Frreze", Q_NULLPTR));
        imageSnapshot->setText(QApplication::translate("GrifoDisplayWidget", "Snapshot", Q_NULLPTR));
        dbgCrs->setText(QApplication::translate("GrifoDisplayWidget", "+", Q_NULLPTR));
        rdrCrs->setText(QApplication::translate("GrifoDisplayWidget", "*", Q_NULLPTR));
#ifndef QT_NO_TOOLTIP
        dbgActions->setToolTip(QApplication::translate("GrifoDisplayWidget", "Remote Debug options", Q_NULLPTR));
#endif // QT_NO_TOOLTIP
        dbgActions->setText(QApplication::translate("GrifoDisplayWidget", "...", Q_NULLPTR));
        lblPos->setText(QApplication::translate("GrifoDisplayWidget", "...", Q_NULLPTR));
        labelInfo->setText(QApplication::translate("GrifoDisplayWidget", "...", Q_NULLPTR));
#endif
    } // retranslateUi
};
//--
class GrifoDisplayWidget::Implementation
{
public:
    Ui_GrifoDisplayWidget* uii;

    QLabel* lblStatus;

    RdrGraphicsScene* scene;

    GrifoDisplayWidget::DbgCrsFlags dbgCrsFlags;
    GrifoDisplayWidget::DbgSymFlags dbgSymFlags;

    int offsetX;
    int offsetY;

    QgVideoRecorder* vcr;

    Implementation()
    {
        dbgCrsFlags=GrifoDisplayWidget::DbgCrsFlagNone;
        offsetX=offsetY=0; //14;
        uii=new Ui_GrifoDisplayWidget;
        vcr=0;
    }
};

#define ui p_.uii

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

    ui->dbgActions->addAction(ui->actionDbgShowAll);
    QAction* a_sep=new QAction(this);
    a_sep->setSeparator(true);

    ui->dbgActions->addAction(a_sep);
    ui->dbgActions->addAction(ui->actionShowReferencePoint);
    ui->dbgActions->addAction(ui->actionShowNearestSymInfo);
    ui->dbgActions->addAction(ui->actionShowLockOnDes);
    ui->dbgActions->addAction(ui->actionMiniZoom);

    a_sep=new QAction(this);
    a_sep->setSeparator(true);
    ui->dbgActions->addAction(a_sep);

    ui->dbgActions->addAction(ui->actionShowAntennaCaret);
    ui->dbgActions->addAction(ui->actionShowAntennaPath);
    ui->dbgActions->addAction(ui->actionHideTgtAlt);
    ui->dbgActions->addAction(ui->actionShowModeInfo);

    ui->zoom->addItem("x1", 1);
    ui->zoom->addItem("x2", 2);
    ui->zoom->addItem("x4", 4);
    ui->zoom->addItem("x8", 8);

    p_.lblStatus=ui->labelInfo;

    ui->rdrView->addAction(ui->actionZoomIn);
    ui->rdrView->addAction(ui->actionZoomOut);
    ui->rdrView->setContextMenuPolicy(Qt::ActionsContextMenu);

    p_.scene=new RdrGraphicsScene(X_DIM/*+128*/, Y_DIM+128);
    p_.scene->setBackgroundBrush(QBrush(Qt::Dense6Pattern));

#if 0
    {
        for(int idx=0;idx<256;idx++)
        {
            p_.scene->ggUpdatePalet(idx, 0xFFFFFF00);
        }
        // TRASPARENT, BKG
        p_.scene->ggUpdatePalet(0, 0xFF969696);
        // OCCLUSION
        p_.scene->ggUpdatePalet(1, 0xFF66421F); //0xFF000000);
        // CAT_A Prio 1
        p_.scene->ggUpdatePalet(2, 0xFFFF0000);
        // CAT_B Prio 2
        p_.scene->ggUpdatePalet(3, 0xFF00FF00);
        // CAT_C Prio 3
        //   Hist 1
        p_.scene->ggUpdatePalet(4, 0xFF00FFFF); // UNK TGT
        p_.scene->ggUpdatePalet(5, 0xFF00FA00); // FRI TGT
        p_.scene->ggUpdatePalet(6, 0xFFFA0000); // FOE TGT
        // CAT_C1 Prio 4
        //   Hist 2
        p_.scene->ggUpdatePalet(7, 0xFF33CCFF); // UNK TGT
        p_.scene->ggUpdatePalet(8, 0xFF00D200); // FRI TGT
        p_.scene->ggUpdatePalet(9, 0xFFD20000); // FOE TGT
        // CAT_C2 Prio 5
        //   Hist 3
        p_.scene->ggUpdatePalet(10, 0xFF3399FF); // UNK TGT
        p_.scene->ggUpdatePalet(11, 0xFF00AC00); // FRI TGT
        p_.scene->ggUpdatePalet(12, 0xFFAC0000); // FOE TGT
        // CAT_C3 Prio 6
        //   Hist 4
        p_.scene->ggUpdatePalet(13, 0xFF0066FF); // UNK TGT
        p_.scene->ggUpdatePalet(14, 0xFF008600); // FRI TGT
        p_.scene->ggUpdatePalet(15, 0xFF860000); // FOE TGT
        // DBG
        //p_.scene->ggUpdatePalet(64, 0xFFFFFFFF);
        //p_.scene->ggUpdatePalet(64, 0xFF66CDAA);
        p_.scene->ggUpdatePalet(64, 0xFFCD853F);
    }
#else
    {
#if 0
        for(int idx=0;idx<256;idx++)
        {
            p_.scene->ggUpdatePalet(idx, 0xFFFFFF00);
        }
        for(int idx=0; idx<16; ++idx)
        {
            p_.scene->ggUpdatePalet(idx, 0xFF000000|(idx<<12));
        }
#endif
        for(int idx=0; idx<128; ++idx)
        {
            unsigned int base_color=(idx*2) & 255; //idx<<4;
            unsigned color=base_color|(base_color<<8)|(base_color<<16);
            color=color|0xFF000000;
            p_.scene->ggUpdatePalet(idx+128, color); //0xFF000000|(idx<<12));
        }
        //p_.scene->ggUpdatePalet(255, 0xFFFFFFFF); //0xFF000000|(idx<<12));

        std::function<void (int idx, unsigned int)> func = [this](int idx, unsigned int v)
        {
            //for(int i=0; i<16; ++i)
            {
                //p_.scene->ggUpdatePalet(i+(idx<<4), v);
                p_.scene->ggUpdatePalet(idx/*+(i<<4)*/, v);
            }
        };
        //func(0, 0xFF969696);
        func(1, 0xFF66421F); //0xFF000000);
        func(2, 0xFFFF0000); //0xFF000000);
        func(3, 0xFF00FF00); //0xFF000000);
        func(4, 0xFF00FFFF); //0xFF000000);
        //func(8, 0xFF00FFFF); //0xFF000000);
        func(5, 0xFF00FA00); // FRI TGT
        func(6, 0xFFFA0000); // FOE TGT
        // CAT_C1 Prio 4
        //   Hist 2
        func(7, 0xFF33CCFF); // UNK TGT
        func(8, 0xFF00D200); // FRI TGT
        func(9, 0xFFD20000); // FOE TGT
        // CAT_C2 Prio 5
        //   Hist 3
        func(10, 0xFF3399FF); // UNK TGT
        func(11, 0xFF00AC00); // FRI TGT
        func(12, 0xFFAC0000); // FOE TGT
        // CAT_C3 Prio 6
        //   Hist 4
        func(13, 0xFF0066FF); // UNK TGT
        func(14, 0xFF008600); // FRI TGT
        func(15, 0xFF860000); // FOE TGT

        func(64, 0xFFCD853F);

#if 0
        // TRASPARENT, BKG
        p_.scene->ggUpdatePalet(0, 0xFF969696);
        // OCCLUSION
        p_.scene->ggUpdatePalet(1, 0xFF66421F); //0xFF000000);
        // CAT_A Prio 1
        p_.scene->ggUpdatePalet(2, 0xFFFF0000);
        // CAT_B Prio 2
        p_.scene->ggUpdatePalet(3, 0xFF00FF00);
        // CAT_C Prio 3
        //   Hist 1
        p_.scene->ggUpdatePalet(4, 0xFF00FFFF); // UNK TGT
        p_.scene->ggUpdatePalet(5, 0xFF00FA00); // FRI TGT
        p_.scene->ggUpdatePalet(6, 0xFFFA0000); // FOE TGT
        // CAT_C1 Prio 4
        //   Hist 2
        p_.scene->ggUpdatePalet(7, 0xFF33CCFF); // UNK TGT
        p_.scene->ggUpdatePalet(8, 0xFF00D200); // FRI TGT
        p_.scene->ggUpdatePalet(9, 0xFFD20000); // FOE TGT
        // CAT_C2 Prio 5
        //   Hist 3
        p_.scene->ggUpdatePalet(10, 0xFF3399FF); // UNK TGT
        p_.scene->ggUpdatePalet(11, 0xFF00AC00); // FRI TGT
        p_.scene->ggUpdatePalet(12, 0xFFAC0000); // FOE TGT
        // CAT_C3 Prio 6
        //   Hist 4
        p_.scene->ggUpdatePalet(13, 0xFF0066FF); // UNK TGT
        p_.scene->ggUpdatePalet(14, 0xFF008600); // FRI TGT
        p_.scene->ggUpdatePalet(15, 0xFF860000); // FOE TGT
        // DBG
        //p_.scene->ggUpdatePalet(64, 0xFFFFFFFF);
        //p_.scene->ggUpdatePalet(64, 0xFF66CDAA);
        p_.scene->ggUpdatePalet(64, 0xFFCD853F);
#endif
    }
#endif
    //ui->localFreeze->setIcon(QIcon());

    //scene->setForegroundBrush(Qt::white);

    //QGraphicImage256* background=new QGraphicImage256(512, 512);
    //scene->addItem(background);
    ui->rdrView->setGeometry(0, 0, X_DIM, Y_DIM); //512, 512);
    //ui->rdrView->setMinimumSize(X_DIM, Y_DIM); //516, 516);
    //ui->rdrView->setMaximumSize(X_DIM, Y_DIM); //516, 516);
    ui->rdrView->setScene(p_.scene);

    connect(ui->localOcclusion, &QToolButton::toggled, this,
            [this](bool checked)
            {
                p_.scene->setBg(checked);
            }
            );
    connect(ui->localFreeze, &QToolButton::toggled, this,
            [this](bool checked)
            {
                //p_.freeze=checked;
                Q_EMIT freezeChanged(checked);
            }
            );


    connect(ui->actionShowReferencePoint, &QAction::toggled, this,
            [this](bool checked)
            {
                p_.dbgCrsFlags.setFlag(DbgCrsFlagShowReferencePoint, checked);
                Q_EMIT dbgCrsFlagsChanged(p_.dbgCrsFlags);
            }
            );
    connect(ui->actionShowNearestSymInfo, &QAction::toggled, this,
            [this](bool checked)
            {
                p_.dbgCrsFlags.setFlag(DbgCrsFlagShowNearestSymInfo, checked);
                Q_EMIT dbgCrsFlagsChanged(p_.dbgCrsFlags);
            }
            );
    connect(ui->actionShowLockOnDes, &QAction::toggled, this,
            [this](bool checked)
            {
                p_.dbgCrsFlags.setFlag(DbgCrsFlagShowLockOnDes, checked);
                Q_EMIT dbgCrsFlagsChanged(p_.dbgCrsFlags);
            }
            );
    connect(ui->actionMiniZoom, &QAction::toggled, this,
            [this](bool checked)
            {
                p_.dbgCrsFlags.setFlag(DbgCrsFlagMiniZoom, checked);
                Q_EMIT dbgCrsFlagsChanged(p_.dbgCrsFlags);
            }
            );
    connect(p_.scene, &RdrGraphicsScene::sigCursorXY, this,
            [this](int x, int y, Qt::KeyboardModifiers mod)
            {
                //Q_EMIT rdrCursorEvent(Qt::MouseButtons, Qt::KeyboardModifiers, int x, int y);
                x-=p_.offsetX;
                y-=p_.offsetY;

                if (mod.testFlag(Qt::ShiftModifier) || (ui->dbgCrs->isChecked()))
                {
                    Q_EMIT dbgCursorSlew(true, x, y);
                }
                if (mod.testFlag(Qt::ControlModifier) || (ui->rdrCrs->isChecked()))
                {
                    Q_EMIT rdrCursorEvent(x, y, 0);
                    //
                }
                QRect r=p_.scene->dbgDeltaPos();
                QPoint cp(r.x(), r.y());
                cp-=QPoint(p_.offsetX, p_.offsetY);
                QPoint d(r.width(), r.height());
                //d-=QPoint(p_.offsetX, p_.offsetY);
                ui->lblPos->setText(QString("(%1,%2) [%3,%4]").arg(cp.x()).arg(cp.y()).arg(d.x()).arg(d.y()));
            }
            );

    connect(ui->zoom, static_cast<void (QComboBox::*)(int index)>(&QComboBox::currentIndexChanged), this,
            [this](int /*index*/)
            {
                static int pzoom=1;
                QVariant v=ui->zoom->currentData();
                int new_zoom=v.toInt();
                if (new_zoom==pzoom)
                    return;
                float scale=float(new_zoom)/pzoom;
                pzoom=new_zoom;
                //qDebug()<<"Z:"<<scale;
                if (scale==1)
                    return;
                ui->rdrView->scale(scale, scale);
            }
            );

    connect(ui->actionZoomIn, &QAction::triggered, this,
            [this]()
            {
                int i=ui->zoom->currentIndex();
                ++i;
                if (i<(ui->zoom->maxCount()-1))
                {
                    ui->zoom->setCurrentIndex(i);
                }
            }
        );
    connect(ui->actionZoomOut, &QAction::triggered, this,
            [this]()
            {
                int i=ui->zoom->currentIndex();
                --i;
                if (i>=0)
                {
                    ui->zoom->setCurrentIndex(i);
                }
            }
        );

    connect(ui->actionDbgShowAll, &QAction::triggered, this, GrifoDisplayWidget::_onActionSymDbg);
    connect(ui->actionShowAntennaCaret, &QAction::triggered, this, GrifoDisplayWidget::_onActionSymDbg);
    connect(ui->actionShowAntennaPath, &QAction::triggered, this, GrifoDisplayWidget::_onActionSymDbg);
    connect(ui->actionHideTgtAlt, &QAction::triggered, this, GrifoDisplayWidget::_onActionSymDbg);
    connect(ui->actionShowModeInfo, &QAction::triggered, this, GrifoDisplayWidget::_onActionSymDbg);

    connect(ui->imageSnapshot, &QToolButton::released, this,
            [this]()
            {
                QString imgname="grifo_snapshot_"+QDateTime::currentDateTime().toString("yyyy-MM-ddd-HH-mm-ss")+".png";
                p_.scene->saveSnapshot(imgname);
            });

    //VCR
    p_.vcr=new QgVideoRecorder(this);

    {
        QIcon vcr_rec=QApplication::style()->standardIcon(QStyle::SP_MediaPlay);
        //QIcon vcr_stop=QApplication::style()->standardIcon(QStyle::SP_MediaStop);

        vcr_rec.addPixmap(
                    QApplication::style()->standardPixmap(QStyle::SP_MediaStop),
                    QIcon::Normal,
                    QIcon::On);

        ui->vcr->setIcon(vcr_rec);

        ui->vcr->setToolTip("Video Recorder");
    }

    connect(ui->vcr, &QToolButton::clicked, [this](bool checked)
    {
        if (checked)
            p_.vcr->recStart();
        else
            p_.vcr->recStop();
    });

    connect(p_.vcr, QgVideoRecorder::vcrTerminated, [this]()
    {
       if (ui->vcr->isChecked())
       {
           ui->vcr->setChecked(false);
       }
    });
}

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

void GrifoDisplayWidget::_onActionSymDbg(bool checked)
{
    QAction* a=qobject_cast<QAction*>(sender());

    //p_.dbgCrsFlags.setFlag(DbgCrsFlagMiniZoom, checked);
    DbgSymFlag flag=(DbgSymFlag)a->data().toUInt();
    p_.dbgSymFlags.setFlag(flag, checked);
    Q_EMIT dbgSymFlagsChanged(p_.dbgSymFlags);
}

//RdrGraphicsScene* GrifoDisplayWidget::graphicsScene()
//{
//    return p_.scene;
//}

void* GrifoDisplayWidget::videoMemory(void) const
{
  return p_.scene->video_memory(); //rdrImage->image.bits();
}

void GrifoDisplayWidget::updatePalette(const uint32_t *p)
{
    for(int i=0; i<256; ++i)
    {
        uint32_t c=p[i];
        c|=0xFF000000;
        p_.scene->ggUpdatePalet(i, c);
    }
}

void GrifoDisplayWidget::updateImage(const void* vb, unsigned int dx, unsigned dy, unsigned int pitch)
{
    typedef unsigned char video_memory_t[1024][1024];

    const char* fb=(const char*)vb;

    if (0)
    {
        static video_memory_t mfd_history[16];
        static unsigned int mfd_pos;
        static unsigned int mfd_crs;
        static unsigned int mfd_depth;

        //video_memory_t* video_memory=mfd_history[mfd_pos];
        unsigned char* p=mfd_history[mfd_pos][0]; //&((*video_memory)[0][0]);
        ///*const unsigned int*/ pitch=512;
        const char* fb=(const char*)vb;
        for(unsigned int i=0; i<dy; ++i, fb+=pitch)
        {
          memcpy(&p[i*1024]/*(*video_memory)[i]*/, fb, dx);
        }
        ++mfd_pos;
        if (mfd_pos>=16)
            mfd_pos=0;
        if (mfd_depth<14)
        {
            mfd_depth+=1;
            return;
        }
        //qDebug()<<"MFD cursor:"<<mfd_crs<<mfd_pos;
        fb=(char*)mfd_history[mfd_crs][0];
        ++mfd_crs;
        if (mfd_crs>=16)
            mfd_crs=0;
    }
    video_memory_t* video_memory=(video_memory_t*)videoMemory(); //scene->video_memory();
    unsigned char* p=&((*video_memory)[0][0]);
    ///*const unsigned int*/ pitch=512;
    //const char* fb=(const char*)vb;
#if 1
    for(unsigned int i=0; i<dy; ++i, fb+=pitch)
    {
      memcpy(&p[i*1024]/*(*video_memory)[i]*/, fb, dx);
    }
#else
    {
        for(int i=0; i<512+128; ++i)
        {
          unsigned long long* p0=reinterpret_cast<unsigned long long*>(&p[i*1024]);
          const unsigned long long* p1=reinterpret_cast<const unsigned long long*>(&fb[i*1024]); //image.scanLine(i));
          for(int j=0; j<((512+128)/8)+1; ++j)
          {
              unsigned long long tmp=p1[j];
              //tmp&=0x0F0F0F0F0F0F0F0F;
              //tmp<<=4;
              p0[j]=tmp; //+p0[j];//+p1[j];
          }
        }
    }

#endif

}

void GrifoDisplayWidget::updateDisplay(bool updateSceneAlso)
{
  p_.scene->ggUpdateImage(); //rdrImage->gg_updated=true;
  if (updateSceneAlso)
      p_.scene->update();

  p_.vcr->addFrame(p_.scene->getImage());
}

void GrifoDisplayWidget::updateScene()
{
    p_.scene->update();
}

void GrifoDisplayWidget::showShortMessage(const QString &str)
{
    p_.lblStatus->setText(str);
}


int GrifoDisplayWidget::offsetX() const
{
    return p_.offsetX;
}

int GrifoDisplayWidget::offsetY() const
{
    return p_.offsetY;
}


void GrifoDisplayWidget::setOffsetX(int x)
{
    p_.offsetX=x;
}

void GrifoDisplayWidget::setOffsetY(int y)
{
    p_.offsetY=y;
}

void GrifoDisplayWidget::setIconFreeze(const QIcon& i)
{
    ui->localFreeze->setIcon(i);
}

void GrifoDisplayWidget::setIconOcclusion(const QIcon& i)
{
    ui->localOcclusion->setIcon(i);
}

void GrifoDisplayWidget::setIconDbgMenu(const QIcon& i)
{
    ui->dbgActions->setIcon(i);
}
