#include "mainwindownew.h"
#include "ui_mainwindownew.h"
#include <QApplication>
#include <QDesktopWidget>

#include "pages/pagedebugprint.h"
#include "settingsextrapage.h"
#include "configparamsgetter.h"

void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QByteArray localMsg = msg.toLocal8Bit();
    QString    str;
    QString    typeStr;
    bool       isBad = false;

    switch (type) {
    case QtDebugMsg: typeStr = "DEBUG"; break;
        //    case QtInfoMsg: typeStr = "INFO"; break;
    case QtWarningMsg: typeStr = "WARNING"; isBad = true; break;
    case QtCriticalMsg: typeStr = "CRITICAL"; isBad = true; break;
    case QtFatalMsg: typeStr = "FATAL"; isBad = true; break;

    default:
        break;
    }

    str.sprintf("%s (%s:%u %s): %s", typeStr.toLocal8Bit().data(), context.file, context.line, context.function,
                localMsg.constData());

    if (DebugPrintPage::currentMsgHandler) {
        QString strTmp;
        if (isBad) {
            strTmp = "<font color=\"red\">" + str + "</font><br>";
        } else {
            strTmp = str + "<br>";
        }

        QMetaObject::invokeMethod(DebugPrintPage::currentMsgHandler, "printConsole", Qt::QueuedConnection,
                                  Q_ARG(QString, strTmp));
    }

    printf("%s\n", str.toLocal8Bit().data());
    fflush(stdout);
}



#if 0

MainWindowNew::MainWindowNew(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindowNew),
    m_currentPageIndex(TabWidgetPage::ConnectWindow)
{
    ui->setupUi(this);

    ui->pbMainMenuBarHideMenu->hide();
    ui->mStatusLabel->hide();

    QLoggingCategory::setFilterRules("qt.network.ssl.warning=false");

    mVersion = QString::number(DT_VERSION);

    //this->setAttribute(Qt::WA_DeleteOnClose);

    initDieBieMs();

    setWindowFlags(Qt::CustomizeWindowHint);
    setFixedSize(mWidth,mHeight);

    m_minimize = false;
    ui->lbHeaderSerialNumberName->setFont(QFont(("Segoe WP SemiLight"), (m_minimize ? 12 : 9) ));
    //ui->lbHeaderSerialNumberName->setVisible(!m_minimize);
    //ui->lbHeaderSerialNumberNameMini->setVisible(!ui->lbHeaderSerialNumberName->isVisible());

    ui->pbMainMenuBarHideMenu     ->setIconStringForButton(":/res/b0L.png");
    ui->pbMainMenuBarAkbMonitor   ->setIconStringForButton(":/res/menu-akb-monitor.png");
    ui->pbMainMenuBarCellsMonitor ->setIconStringForButton(":/res/menu-cells-monitor.png");
    ui->pbMainMenuBarConfiguration->setIconStringForButton(":/res/menu-configuration.png");
    ui->pbMainMenuBarVisualization->setIconStringForButton(":/res/menu-visualization.png");
    ui->pbMainMenuBarHistory      ->setIconStringForButton(":/res/menu-history.png");
    ui->pbMainMenuBarSeriveOfBms  ->setIconStringForButton(":/res/menu-serive-of-bms.png");
    ui->pbMainMenuBarSettingsExtra->setIconStringForButton(":/res/menu-settings-extra.png");
    ui->pbMainMenuBarExit         ->setIconStringForButton(":/res/menu-exit.png");

    /*
    //m_btnGroupMainMenuBar = new QButtonGroup(this);
    m_btnGroupMainMenuBar->addButton(ui->pbMainMenuBarHideMenu     );
    m_btnGroupMainMenuBar->addButton(ui->pbMainMenuBarAkbMonitor   );
    m_btnGroupMainMenuBar->addButton(ui->pbMainMenuBarCellsMonitor );
    m_btnGroupMainMenuBar->addButton(ui->pbMainMenuBarConfiguration);
    m_btnGroupMainMenuBar->addButton(ui->pbMainMenuBarVisualization);
    m_btnGroupMainMenuBar->addButton(ui->pbMainMenuBarHistory      );
    m_btnGroupMainMenuBar->addButton(ui->pbMainMenuBarSeriveOfBms  );
    m_btnGroupMainMenuBar->addButton(ui->pbMainMenuBarExit         );
    */
    connect(ui->pbMainMenuBarAkbMonitor,    &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = AkbMonitor;    selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarCellsMonitor,  &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = CellsMonitor;  selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarConfiguration, &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = Configuration; selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarVisualization, &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = Visualization; selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarHistory,       &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = History;       selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarSeriveOfBms,   &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = SeriveOfBms;   selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarSettingsExtra, &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = SettingsExtra; selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarExit,          &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = ConnectWindow; selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );

    //connect(ui->pbMainMenuBarVisualization, &QPushButton::clicked, ui->tabVisualization, &VisualizationPage::onVisualizationPageSelected);

    initAnimationForLeftTabsBar();

    connect(ui->pbMainMenuBarHideMenu, &QPushButton::clicked, this, &MainWindowNew::onShrink);

    //connect(m_btnGroupMainMenuBar, QOverload<QAbstractButton *>::of(&QButtonGroup::buttonClicked), this, &MainWindowNew::onMainMenuBarButtonClicked);

    //onHideAndShowConnectWindowAgain();

    connect(ui->tabConfiguration, &ConfigurationPage::sendMessage, ui->tabSeriveOfBms, &BmsServicePage::printReceived);

    //connect(ui->pbMainMenuBarExit, &QPushButton::clicked, this, [=]() { QApplication::quit(); } );
    connect(ui->tabConnect, &ConnectAndEnterPage::sigConnected, this, &MainWindowNew::onHideConnectWindow );
    connect(ui->tabConnect, &ConnectAndEnterPage::sigReject, this, [=]() { QApplication::quit(); } );
    connect(ui->pbMainMenuBarExit, &QPushButton::clicked, this, &MainWindowNew::onShowConnectWindow);
    //connect(this, &MainWindowNew::sigShowConnectWindow, this, &MainWindowNew::onShowConnectWindow);

    //prepareWindowBeforeShow


    //* // ENABLE WHEN FINISHED
    connect(this, &MainWindowNew::loadParams, ui->tabAkbMonitor, &AkbMonitorPage::onLoadParams);
    connect(this, &MainWindowNew::loadParams, ui->tabConfiguration, &ConfigurationPage::loadParams);
    //*/

    //if(mSerialPort->isOpen()) {


    //emit sigShowConnectWindow();
    onShowConnectWindow();

    mPageDebugPrint->printConsole("DieBieMSTool " + mVersion + " started<br>");
}

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



void MainWindowNew::initDieBieMs()
{
    // mVersion = QString::number(DT_VERSION);
    mDieBieMS       = new BMSInterface(this);

    ui->tabConnect->initDieBieMS(mDieBieMS);
    //ui->tabConnect->setDieBieMS(mDieBieMS);
    ui->tabAkbMonitor->setDieBieMS(mDieBieMS);
    ui->tabCellsMonitor->setDieBieMS(mDieBieMS);
    ui->tabConfiguration->setDieBieMS(mDieBieMS);
    ui->tabVisualization->setDieBieMS(mDieBieMS);
    ui->tabHistory->setDieBieMS(mDieBieMS);
    ui->tabSeriveOfBms->setDieBieMS(mDieBieMS);
    //ui->tabSettingsExtra->setDieBieMS(mDieBieMS);

    mPageDebugPrint = ui->tabHistory;
    ui->tabConfiguration->setDebugPrintPage(mPageDebugPrint);

    // init everything for Real time watching and updating info
    mStatusInfoTime = 0;
    ui->mStatusLabel->clear(); // = new QLabel(this);
    //ui->statusBar->addPermanentWidget(mStatusLabel);
    mMcConfRead = false;


    mTimer      = new QTimer(this);
    connect(mTimer, &QTimer::timeout, this, &MainWindowNew::onTimerSlot);
    mTimer->start(20);
    // init everything for Real time watching and updating info

    connect(ui->tabSettingsExtra, &SettingsExtraPage::connected, this, [=]() {
        const QString greenStyle = "color: lime; \
                background-color: lime; \
                border-color: lime; \
                border-width: 0px; \
                border-style: solid; \
                border-radius: 10px;";

                ui->lbHeaderConnectionIndicator->setStyleSheet(greenStyle);
    } );

    connect(ui->tabSettingsExtra, &SettingsExtraPage::disconnected, this, [=]() {
        const QString redStyle = "color: red; \
                        background-color: red; \
                        border-color: red; \
                        border-width: 0px; \
                        border-style: solid; \
                        border-radius: 10px;";

        ui->lbHeaderConnectionIndicator->setStyleSheet(redStyle);
    } );

    connect(this, &MainWindowNew::loadParams, ui->tabConfiguration, &ConfigurationPage::loadParams);
}

/////////////////////////////////////


void MainWindowNew::onTimerSlot()
{
    // Update status label
    if (mStatusInfoTime) {
        mStatusInfoTime--;
        if (!mStatusInfoTime) {
            //ui->mStatusLabel->setStyleSheet(qApp->styleSheet());
        }
    } else {
        QString str = mDieBieMS->getConnectedPortName();
        if (str != ui->mStatusLabel->text()) {
            ui->mStatusLabel->setText(mDieBieMS->getConnectedPortName());
            static QString statusLast = "";
            if (str != statusLast) {
                mPageDebugPrint->printConsole("Status: " + str + "<br>");
                statusLast = str;
            }
        }
    }

    // CAN fwd // actionCanFwd
    //if (ui->actionCanFwd->isChecked() != mDieBieMS->commands()->getSendCan()) {
    //    ui->actionCanFwd->setChecked(mDieBieMS->commands()->getSendCan());
    //}


    // Visualisation
    // RT data only every 5 iterations // actionRtData // REALTIME DATA
    ui->tabVisualization->setIsPageActivated(ui->pbMainMenuBarVisualization->isChecked());
    if ( ui->pbMainMenuBarVisualization->isChecked() || ui->pbMainMenuBarAkbMonitor->isChecked() || ui->pbMainMenuBarCellsMonitor->isChecked() )
    {
        static int values_cnt = 0;
        static int cells_cnt  = 0;

        values_cnt++;
        if (values_cnt >= 5) {
            values_cnt = 0;
            mDieBieMS->commands()->getValues();
        }

        cells_cnt++;
        if (cells_cnt >= 20) {
            cells_cnt = 0;
            mDieBieMS->commands()->getCells();
        }
    }

    // Send alive command once every 10 iterations // actionSendAlive
    if (false) //ui->actionSendAlive->isChecked())
    {
        static int alive_cnt = 0;
        alive_cnt++;
        if (alive_cnt >= 10) {
            alive_cnt = 0;
            mDieBieMS->commands()->sendAlive();
        }
    }

    // Read configuration it isn't read since starting VESC Tool
    if (mDieBieMS->isPortConnected()) {
        static int conf_cnt = 0;
        conf_cnt++;
        if (conf_cnt >= 20) {
            conf_cnt = 0;
            if (!mMcConfRead) {
                mDieBieMS->commands()->getBMSconf();
            }
        }
    }

    // Disable all data streaming when uploading firmware
    if (mDieBieMS->commands()->getFirmwareUploadProgress() > 0.1) {
        //ui->actionSendAlive->setChecked(false);
        //ui->actionRtData->setChecked(false);
        if(!isConnectWindowActivated())
            ui->pbMainMenuBarAkbMonitor->clicked();
    }

    // Run startup checks
    static bool has_run_start_checks = false;
    if (!has_run_start_checks) {
        has_run_start_checks = true;
        checkUdev();

#if ENABLE_VERSION_CHECK
        Utility::checkVersion(mDieBieMS);
#endif

    }

}



void MainWindowNew::showStatusInfo(QString info, bool isGood)
{
    if (isGood) {
        ui->mStatusLabel->setStyleSheet("QLabel { background-color : lightgreen; color : black; }");
        mPageDebugPrint->printConsole("Status: " + info + "<br>");
    } else {
        ui->mStatusLabel->setStyleSheet("QLabel { background-color : red; color : black; }");
        mPageDebugPrint->printConsole("<font color=\"red\">Status: " + info + "</font><br>");
    }

    mStatusInfoTime = 80;
    ui->mStatusLabel->setText(info);
}


/////////////////////////////////////

bool MainWindowNew::isConnectWindowActivated() const
{
    return (m_currentPageIndex == TabWidgetPage::ConnectWindow);
}

void MainWindowNew::bmsconfUpdated()
{
    mMcConfRead = true;
}


void MainWindowNew::checkUdev()
{
    // Check if udev rules for modemmanager are installed
#ifdef Q_OS_LINUX
    QFileInfo fi_mm("/lib/udev/rules.d/77-mm-usb-device-blacklist.rules");
    if (fi_mm.exists()) {
        QFileInfo fi_bms("/lib/udev/rules.d/45-vesc.rules");
        if (!fi_vesc.exists()) {
            QMessageBox::StandardButton reply;
            reply = QMessageBox::information(this,
                                             tr("Modemmenager"),
                                             tr("It looks like modemmanager is installed on your system, and that "
                                                "there are no VESC udev rules installed. This will cause a delay "
                                                "from when you plug in the VESC until you can use it. Would you like "
                                                "to add a udev rule to prevent modemmanager from grabbing the VESC?"),
                                             QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);

            if (reply == QMessageBox::Yes) {
                QFile f_bms(QDir::temp().absoluteFilePath(fi_vesc.fileName()));
                if (!f_vesc.open(QIODevice::WriteOnly | QIODevice::Text)) {
                    showMessageDialog(tr("Create File Error"),
                                      f_vesc.errorString(),
                                      false, false);
                    return;
                }

                f_vesc.write("# Prevent modemmanager from grabbing the VESC\n"
                             "ATTRS{idVendor}==\"0483\", ATTRS{idProduct}==\"5740\", ENV{ID_MM_DEVICE_IGNORE}=\"1\"\n");
                f_vesc.close();

                QFileInfo fi_new(f_vesc);
                QProcess process;
                process.setEnvironment(QProcess::systemEnvironment());
                process.start("pkexec", QStringList() <<
                              "mv" <<
                              fi_new.absoluteFilePath() <<
                              fi_vesc.absolutePath());
                waitProcess(process);

                if (process.exitCode() == 0) {
                    QMessageBox::StandardButton reply;
                    reply = QMessageBox::information(this,
                                                     tr("Modemmenager"),
                                                     tr("The udev rule was created successfully. Would you like "
                                                        "to reload udev to apply the new rule?"),
                                                     QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);

                    if (reply == QMessageBox::Yes) {
                        QProcess process;
                        process.setEnvironment(QProcess::systemEnvironment());
                        process.start("pkexec", QStringList() <<
                                      "udevadm" <<
                                      "control" <<
                                      "--reload-rules");
                        waitProcess(process);

                        if (process.exitCode() == 0) {
                            showMessageDialog(tr("Command Result"),
                                              tr("Reloaded udev rules sucessfully."),
                                              true, false);
                        } else {
                            QString out = process.readAll();

                            if (out.isEmpty()) {
                                showMessageDialog(tr("Command Result"),
                                                  tr("Could not reload udev rules. A reboot is probably "
                                                     "required for this change to take effect."),
                                                  false, false);
                            }
                        }
                        process.close();
                    }
                } else {
                    showMessageDialog(tr("Command Result"),
                                      tr("Could not move rules file:\n\n"
                                         "%1").
                                      arg(QString(process.readAllStandardOutput())),
                                      false, false);
                }
                process.close();
            }
        }
    }
#endif
}



//void MainWindowNew::onHideThisAndShowConnectWindow()
//{
//    ui->tabConnect->prepareWindowBeforeShow();
//}

/*
void MainWindowNew::onShowConnectWindow()
{
    mConnect.prepareWindowBeforeShow();

    if(mConnect.exec() == QDialog::Rejected)
    {
        isConnectionPrepared = false;
    }
    else
    {
        isConnectionPrepared = mConnect.isConnectionPrepared();
        comPortToConnect     = mConnect.portToConnect();
    }

    if(isConnectionPrepared)
    {
        mConnect.hide();
        show();
        emit loadParams();
    }
    else {
        close();
        QApplication::quit();
    }
}
*/

void MainWindowNew::onShowConnectWindow()
{
    mIsConnectionPrepared = false;
    mComPortToConnect.clear();

    setAllMainMenuBarButtonsVisible(false);
    unselectAllLeftTabBarButtons();

    m_currentPageIndex = TabWidgetPage::ConnectWindow;
    ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex);

    ui->tabWidgetPagesContent->setGeometry(0, -10, mWidth, 751);

    ui->tabConnect->prepareWindowBeforeShow();
    setLeftTopWidgetsVisible(false);
}

void MainWindowNew::onHideConnectWindow()
{
    mIsConnectionPrepared = ui->tabConnect->isConnectionPrepared();
    mComPortToConnect     = ui->tabConnect->portToConnect();

    m_currentPageIndex = TabWidgetPage::AkbMonitor;
    ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex);

    setAllMainMenuBarButtonsVisible(true);
    selectCurrentLeftTabBarButton();

    ui->tabWidgetPagesContent->setGeometry(280, -10, 1084, 751);

    setLeftTopWidgetsVisible(true);
    emit loadParams();
}


void MainWindowNew::setLeftTopWidgetsVisible(bool value)
{
    ui->lbHeaderConnectionName      ->setVisible(value);
    ui->lbHeaderConnectionIndicator ->setVisible(value);
    ui->lbHeaderBmsVersion          ->setVisible(value);
    ui->lbHeaderSerialNumberName    ->setVisible(value);
    ui->lbHeaderSerialNumberValue   ->setVisible(value);
    ui->labHeaderSeparator          ->setVisible(value);
    ui->lbHeaderLanguageName        ->setVisible(value);
    ui->lbHeaderLanguageIcon        ->setVisible(value);
}

void MainWindowNew::setAllMainMenuBarButtonsVisible(bool val)
{
    ui->pbMainMenuBarAkbMonitor   ->setVisible(val);
    ui->pbMainMenuBarCellsMonitor ->setVisible(val);
    ui->pbMainMenuBarConfiguration->setVisible(val);
    ui->pbMainMenuBarVisualization->setVisible(val);
    ui->pbMainMenuBarHistory      ->setVisible(val);
    ui->pbMainMenuBarSeriveOfBms  ->setVisible(val);
    ui->pbMainMenuBarSettingsExtra->setVisible(val);
    ui->pbMainMenuBarExit         ->setVisible(val);
}

void MainWindowNew::unselectAllLeftTabBarButtons()
{
    ui->pbMainMenuBarAkbMonitor   ->setChecked(false);
    ui->pbMainMenuBarCellsMonitor ->setChecked(false);
    ui->pbMainMenuBarConfiguration->setChecked(false);
    ui->pbMainMenuBarVisualization->setChecked(false);
    ui->pbMainMenuBarHistory      ->setChecked(false);
    ui->pbMainMenuBarSeriveOfBms  ->setChecked(false);
    ui->pbMainMenuBarSettingsExtra->setChecked(false);
    ui->pbMainMenuBarExit         ->setChecked(false);
}

void MainWindowNew::selectCurrentLeftTabBarButton()
{
    switch (m_currentPageIndex) {
    case AkbMonitor   : ui->pbMainMenuBarAkbMonitor   ->setChecked(true); break;
    case CellsMonitor : ui->pbMainMenuBarCellsMonitor ->setChecked(true); break;
    case Configuration: ui->pbMainMenuBarConfiguration->setChecked(true); break;
    case Visualization: ui->pbMainMenuBarVisualization->setChecked(true); break;
    case History      : ui->pbMainMenuBarHistory      ->setChecked(true); break;
    case SeriveOfBms  : ui->pbMainMenuBarSeriveOfBms  ->setChecked(true); break;
    case SettingsExtra: ui->pbMainMenuBarSettingsExtra->setChecked(true); break;
    //case Exit       : ui->pbMainMenuBarExit         ->setChecked(true); break;
    case ConnectWindow: break;
    };
}


//void MainWindowNew::onMainMenuBarButtonClicked()
//{
    // WARNING !!!
    // Do NOT set any Left Tab Bar Button checked inside of the UI-file
    // If you do so, then even after you will use method unselectAllLeftTabBarButtons()
    //  if(!btn->isChecked())
    //      continue;
    // THIS if() will not go to continue call, it will be skipped
    //           exactrly on that Left Tab Bar Button that you have checked inside of the UI-file
    // UI has for some reason a HIGHER proiority over programmaticly set ->setChecked() method ...

    //for(auto btn: m_btnGroupMainMenuBar->buttons())
    //{
/*
        if(!btn->isChecked())
            continue;

        if     ( btn->objectName() == ui->pbMainMenuBarAkbMonitor   ->objectName() ) m_currentPageIndex = AkbMonitor    ;
        else if( btn->objectName() == ui->pbMainMenuBarCellsMonitor ->objectName() ) m_currentPageIndex = CellsMonitor  ;
        else if( btn->objectName() == ui->pbMainMenuBarConfiguration->objectName() ) m_currentPageIndex = Configuration ;
        else if( btn->objectName() == ui->pbMainMenuBarVisualization->objectName() ) m_currentPageIndex = Visualization ;
        else if( btn->objectName() == ui->pbMainMenuBarHistory      ->objectName() ) m_currentPageIndex = History       ;
        else if( btn->objectName() == ui->pbMainMenuBarSeriveOfBms  ->objectName() ) m_currentPageIndex = SeriveOfBms   ;

        ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex);
        return;
    //}

    m_currentPageIndex = ConnectWindow;
    ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex);
*/
//}

/////////////////////////////////////


void MainWindowNew::onShrink()
{
    if (m_minimize) {
        clearAllBtnsText();
        m_animgroupMin->start();
        ui->pbMainMenuBarHideMenu->setIconStringForButton(":/res/b0R.png");
        ui->lbHeaderSerialNumberName->setFont(QFont(("Segoe WP SemiLight"), 12 ));
    }
    else {
        restoreAllBtnsText();
        m_animgroupMax->start();
        ui->pbMainMenuBarHideMenu->setIconStringForButton(":/res/b0L.png");
        ui->lbHeaderSerialNumberName->setFont(QFont(("Segoe WP SemiLight"), 9) );
    }

    m_minimize = !m_minimize;
}

void MainWindowNew::initAnimationForLeftTabsBar()
{
    m_logoWay      = 65;
    int sec        = 1000;
    int min        = 100;
    int max        = 281;
    int fromShrink = max;
    int toShrink   = min;
    int fromMax    = min;
    int toMax      = max;

    m_minimize = true;
    m_animgroupMin = new QParallelAnimationGroup;
    m_animgroupMax = new QParallelAnimationGroup;

    QPropertyAnimation *aminL = new QPropertyAnimation(ui->lbIconLogo, "geometry");
    QPropertyAnimation *aminB = new QPropertyAnimation(ui->labLeftTabListBackground, "geometry");
    QPropertyAnimation *amin0 = new QPropertyAnimation(ui->pbMainMenuBarHideMenu     , "geometry");
    QPropertyAnimation *amin1 = new QPropertyAnimation(ui->pbMainMenuBarAkbMonitor   , "geometry");
    QPropertyAnimation *amin2 = new QPropertyAnimation(ui->pbMainMenuBarCellsMonitor , "geometry");
    QPropertyAnimation *amin3 = new QPropertyAnimation(ui->pbMainMenuBarConfiguration, "geometry");
    QPropertyAnimation *amin4 = new QPropertyAnimation(ui->pbMainMenuBarVisualization, "geometry");
    QPropertyAnimation *amin5 = new QPropertyAnimation(ui->pbMainMenuBarHistory      , "geometry");
    QPropertyAnimation *amin6 = new QPropertyAnimation(ui->pbMainMenuBarSeriveOfBms  , "geometry");
    QPropertyAnimation *amin7 = new QPropertyAnimation(ui->pbMainMenuBarSettingsExtra  , "geometry");
    QPropertyAnimation *amin8 = new QPropertyAnimation(ui->pbMainMenuBarExit         , "geometry");
    QPropertyAnimation *amin9 = new QPropertyAnimation(ui->mStatusLabel         , "geometry");


    QPropertyAnimation *amaxL = new QPropertyAnimation(ui->lbIconLogo, "geometry");
    QPropertyAnimation *amaxB = new QPropertyAnimation(ui->labLeftTabListBackground, "geometry");
    QPropertyAnimation *amax0 = new QPropertyAnimation(ui->pbMainMenuBarHideMenu     , "geometry");
    QPropertyAnimation *amax1 = new QPropertyAnimation(ui->pbMainMenuBarAkbMonitor   , "geometry");
    QPropertyAnimation *amax2 = new QPropertyAnimation(ui->pbMainMenuBarCellsMonitor , "geometry");
    QPropertyAnimation *amax3 = new QPropertyAnimation(ui->pbMainMenuBarConfiguration, "geometry");
    QPropertyAnimation *amax4 = new QPropertyAnimation(ui->pbMainMenuBarVisualization, "geometry");
    QPropertyAnimation *amax5 = new QPropertyAnimation(ui->pbMainMenuBarHistory      , "geometry");
    QPropertyAnimation *amax6 = new QPropertyAnimation(ui->pbMainMenuBarSeriveOfBms  , "geometry");
    QPropertyAnimation *amax7 = new QPropertyAnimation(ui->pbMainMenuBarSettingsExtra  , "geometry");
    QPropertyAnimation *amax8 = new QPropertyAnimation(ui->pbMainMenuBarExit         , "geometry");
    QPropertyAnimation *amax9 = new QPropertyAnimation(ui->mStatusLabel         , "geometry");

    setAnimLogoMin  ( m_animgroupMin, aminL, sec, ui->lbIconLogo );
    setAnimParamsMin( m_animgroupMin, aminB, sec, ui->labLeftTabListBackground );
    setAnimParamsMin( m_animgroupMin, amin0, sec, ui->pbMainMenuBarHideMenu      );
    setAnimParamsMin( m_animgroupMin, amin1, sec, ui->pbMainMenuBarAkbMonitor    );
    setAnimParamsMin( m_animgroupMin, amin2, sec, ui->pbMainMenuBarCellsMonitor  );
    setAnimParamsMin( m_animgroupMin, amin3, sec, ui->pbMainMenuBarConfiguration );
    setAnimParamsMin( m_animgroupMin, amin4, sec, ui->pbMainMenuBarVisualization );
    setAnimParamsMin( m_animgroupMin, amin5, sec, ui->pbMainMenuBarHistory       );
    setAnimParamsMin( m_animgroupMin, amin6, sec, ui->pbMainMenuBarSeriveOfBms   );
    setAnimParamsMin( m_animgroupMin, amin7, sec, ui->pbMainMenuBarSettingsExtra   );
    setAnimParamsMin( m_animgroupMin, amin8, sec, ui->pbMainMenuBarExit          );
    setAnimParamsMin( m_animgroupMin, amin9, sec, ui->mStatusLabel          );

    setAnimLogoMax  ( m_animgroupMax, amaxL, sec, ui->lbIconLogo );
    setAnimParamsMax( m_animgroupMax, amaxB, sec, ui->labLeftTabListBackground );
    setAnimParamsMax( m_animgroupMax, amax0, sec, ui->pbMainMenuBarHideMenu      );
    setAnimParamsMax( m_animgroupMax, amax1, sec, ui->pbMainMenuBarAkbMonitor    );
    setAnimParamsMax( m_animgroupMax, amax2, sec, ui->pbMainMenuBarCellsMonitor  );
    setAnimParamsMax( m_animgroupMax, amax3, sec, ui->pbMainMenuBarConfiguration );
    setAnimParamsMax( m_animgroupMax, amax4, sec, ui->pbMainMenuBarVisualization );
    setAnimParamsMax( m_animgroupMax, amax5, sec, ui->pbMainMenuBarHistory       );
    setAnimParamsMax( m_animgroupMax, amax6, sec, ui->pbMainMenuBarSeriveOfBms   );
    setAnimParamsMax( m_animgroupMax, amax7, sec, ui->pbMainMenuBarSettingsExtra   );
    setAnimParamsMax( m_animgroupMax, amax8, sec, ui->pbMainMenuBarExit          );
    setAnimParamsMax( m_animgroupMax, amax9, sec, ui->mStatusLabel          );

    //connect(ui->pushButton_13, &QPushButton::clicked, this, &MainWindowNew::onShrink);
}


void MainWindowNew::setAnimParams(QParallelAnimationGroup *group, QPropertyAnimation *a, int sec, int from,
                                          int to)
{
    a->setDuration(sec);
    a->setStartValue(from);
    a->setEndValue(to);
    a->setEasingCurve(QEasingCurve::Linear);
    group->addAnimation(a);
}

void MainWindowNew::clearAllBtnsText()
{
    //clearBtnText();
    clearBtnText( ui->pbMainMenuBarHideMenu       );
    clearBtnText( ui->pbMainMenuBarAkbMonitor     );
    clearBtnText( ui->pbMainMenuBarCellsMonitor   );
    clearBtnText( ui->pbMainMenuBarConfiguration  );
    clearBtnText( ui->pbMainMenuBarVisualization  );
    clearBtnText( ui->pbMainMenuBarHistory        );
    clearBtnText( ui->pbMainMenuBarSeriveOfBms    );
    clearBtnText( ui->pbMainMenuBarSettingsExtra    );
    clearBtnText( ui->pbMainMenuBarExit           );
}
void MainWindowNew::restoreAllBtnsText()
{
    restoreBtnText( ui->pbMainMenuBarHideMenu       );
    restoreBtnText( ui->pbMainMenuBarAkbMonitor     );
    restoreBtnText( ui->pbMainMenuBarCellsMonitor   );
    restoreBtnText( ui->pbMainMenuBarConfiguration  );
    restoreBtnText( ui->pbMainMenuBarVisualization  );
    restoreBtnText( ui->pbMainMenuBarHistory        );
    restoreBtnText( ui->pbMainMenuBarSeriveOfBms    );
    restoreBtnText( ui->pbMainMenuBarSettingsExtra    );
    restoreBtnText( ui->pbMainMenuBarExit           );
}

void MainWindowNew::clearBtnText(CustomLeftTabBarButton *btn)
{
    btn->setProperty("tmp", btn->text());
    btn->setText("");
}
void MainWindowNew::restoreBtnText(CustomLeftTabBarButton *btn)
{
    btn->setText(btn->property("tmp").toString());
}



void MainWindowNew::setAnimLogoMin(QParallelAnimationGroup *group, QPropertyAnimation *a, int sec, QLabel *obj)
{
    a->setDuration(sec);
    QRect rec = obj->geometry();
    a->setStartValue(QRect(rec.x(), rec.y(), rec.width(), rec.height()));
    a->setEndValue(QRect(rec.x()-m_logoWay, rec.y()/2, rec.width(), rec.height()));
    a->setEasingCurve(QEasingCurve::Linear);
    group->addAnimation(a);
}
void MainWindowNew::setAnimLogoMax(QParallelAnimationGroup *group, QPropertyAnimation *a, int sec, QLabel *obj)
{
    a->setDuration(sec);
    QRect rec = obj->geometry();
    a->setStartValue(QRect(rec.x()-m_logoWay, rec.y()/2, rec.width(), rec.height()));
    a->setEndValue(QRect(rec.x(), rec.y(), rec.width(), rec.height()));
    a->setEasingCurve(QEasingCurve::Linear);
    group->addAnimation(a);
}

void MainWindowNew::setAnimParamsMin(QParallelAnimationGroup *group, QPropertyAnimation *a, int sec, QLabel *obj)
{
    a->setDuration(sec);
    QRect rec = obj->geometry();
    a->setStartValue(QRect(rec.x(), rec.y(), rec.width(), rec.height()));
    a->setEndValue(QRect(rec.x(), rec.y(), rec.width()/2, rec.height()));
    a->setEasingCurve(QEasingCurve::Linear);
    group->addAnimation(a);
}
void MainWindowNew::setAnimParamsMax(QParallelAnimationGroup *group, QPropertyAnimation *a, int sec, QLabel *obj)
{
    a->setDuration(sec);
    QRect rec = obj->geometry();
    a->setStartValue(QRect(rec.x(), rec.y(), rec.width()/2, rec.height()));
    a->setEndValue(QRect(rec.x(), rec.y(), rec.width(), rec.height()));
    a->setEasingCurve(QEasingCurve::Linear);
    group->addAnimation(a);
}

void MainWindowNew::setAnimParamsMin(QParallelAnimationGroup *group, QPropertyAnimation *a, int sec, CustomLeftTabBarButton *btn)
{
    a->setDuration(sec);
    QRect rec = btn->geometry();
    a->setStartValue(QRect(rec.x(), rec.y(), rec.width(), rec.height()));
    a->setEndValue(QRect(rec.x(), rec.y(), rec.width()/2, rec.height()));
    a->setEasingCurve(QEasingCurve::Linear);
    group->addAnimation(a);
}
void MainWindowNew::setAnimParamsMax(QParallelAnimationGroup *group, QPropertyAnimation *a, int sec, CustomLeftTabBarButton *btn)
{
    a->setDuration(sec);
    QRect rec = btn->geometry();
    a->setStartValue(QRect(rec.x(), rec.y(), rec.width()/2, rec.height()));
    a->setEndValue(QRect(rec.x(), rec.y(), rec.width(), rec.height()));
    a->setEasingCurve(QEasingCurve::Linear);
    group->addAnimation(a);
}

//////////////////////////////////////////////////////////////////////
///
//////////////////////////////////////////////////////////////////////




bool MainWindowNew::addParamRow(ConfigParams *params, QString paramName)
{
    bool res = false;
    QWidget *editor = params->getEditor(paramName);
    QString name = params->getLongName(paramName);

    if (editor) {
        //int row = rowCount();
        //setRowCount(row + 1);
        //QTableWidgetItem *item = new QTableWidgetItem(name);
        //item->setFlags(item->flags() & ~Qt::ItemIsEditable);
        //setItem(row, 0, item);
        //setCellWidget(row, 1, editor);

        res = true;
        //resizeColumnToContents(0);
        //resizeRowsToContents();
    }

    return res;
}

#endif



#include <QApplication>
#include <QMessageBox>
#include <QFileDialog>

#include "pages/pagedebugprint.h"
#include "settingsextrapage.h"
#include "widgets/paramdialog.h"



void MainWindowNew::showWindowInOneStaticPlaceWithoutHideResizeCloseButtons()
{
    setWindowFlags(Qt::FramelessWindowHint);
}

void MainWindowNew::setAppSizeForFullView()
{
    setFixedSize(mWidth,mHeight);
}

void MainWindowNew::setAppSizeForConnectionPage()
{
     setFixedSize(mWidthConnectPage,mHeightConnectPage);
}

void MainWindowNew::moveApplicationToTheCenter()
{
    move(QApplication::desktop()->screen()->rect().center() - rect().center());
}

//*
MainWindowNew::MainWindowNew(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindowNew)
{
    ui->setupUi(this);

#if RELEASE_VERSION
    showWindowInOneStaticPlaceWithoutHideResizeCloseButtons();
#endif
    setAppSizeForConnectionPage();
    moveApplicationToTheCenter();

    //////////////////////////////////////////////////////
    /// mainwindownew
    //ui->setupUi(this);

    ui->pbMainMenuBarHideMenu->hide();
    ui->mStatusLabel->hide();

    QLoggingCategory::setFilterRules("qt.network.ssl.warning=false");

    mVersion = QString::number(DT_VERSION);

    //this->setAttribute(Qt::WA_DeleteOnClose);

    ///initDieBieMs();

    //setWindowFlags(Qt::CustomizeWindowHint);
    //setFixedSize(mWidth,mHeight);

    m_minimize = false;
    ui->lbHeaderSerialNumberName->setFont(QFont(("Segoe WP SemiLight"), (m_minimize ? 12 : 9) ));
    //ui->lbHeaderSerialNumberName->setVisible(!m_minimize);
    //ui->lbHeaderSerialNumberNameMini->setVisible(!ui->lbHeaderSerialNumberName->isVisible());

    ui->pbMainMenuBarHideMenu     ->setIconStringForButton(":/res/b0L.png");
    ui->pbMainMenuBarAkbMonitor   ->setIconStringForButton(":/res/menu-akb-monitor.png");
    ui->pbMainMenuBarCellsMonitor ->setIconStringForButton(":/res/menu-cells-monitor.png");
    ui->pbMainMenuBarConfiguration->setIconStringForButton(":/res/menu-configuration.png");
    ui->pbMainMenuBarVisualization->setIconStringForButton(":/res/menu-visualization.png");
    ui->pbMainMenuBarHistory      ->setIconStringForButton(":/res/menu-history.png");
    ui->pbMainMenuBarSeriveOfBms  ->setIconStringForButton(":/res/menu-serive-of-bms.png");
    ui->pbMainMenuBarSettingsExtra->setIconStringForButton(":/res/menu-settings-extra.png");
    ui->pbMainMenuBarExit         ->setIconStringForButton(":/res/menu-exit.png");

    /*
    //m_btnGroupMainMenuBar = new QButtonGroup(this);
    m_btnGroupMainMenuBar->addButton(ui->pbMainMenuBarHideMenu     );
    m_btnGroupMainMenuBar->addButton(ui->pbMainMenuBarAkbMonitor   );
    m_btnGroupMainMenuBar->addButton(ui->pbMainMenuBarCellsMonitor );
    m_btnGroupMainMenuBar->addButton(ui->pbMainMenuBarConfiguration);
    m_btnGroupMainMenuBar->addButton(ui->pbMainMenuBarVisualization);
    m_btnGroupMainMenuBar->addButton(ui->pbMainMenuBarHistory      );
    m_btnGroupMainMenuBar->addButton(ui->pbMainMenuBarSeriveOfBms  );
    m_btnGroupMainMenuBar->addButton(ui->pbMainMenuBarExit         );
    */

    /*
    connect(ui->pbMainMenuBarAkbMonitor,    &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = AkbMonitor;    selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarCellsMonitor,  &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = CellsMonitor;  selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarConfiguration, &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = Configuration; selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarVisualization, &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = Visualization; selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarHistory,       &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = History;       selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarSeriveOfBms,   &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = SeriveOfBms;   selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarSettingsExtra, &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = SettingsExtra; selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarExit,          &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = ConnectWindow; selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    */

    connect(ui->pbMainMenuBarAkbMonitor,    &QPushButton::clicked, this, &MainWindowNew::onAnyLeftTabBarButtonClicked);
    connect(ui->pbMainMenuBarCellsMonitor,  &QPushButton::clicked, this, &MainWindowNew::onAnyLeftTabBarButtonClicked);
    connect(ui->pbMainMenuBarConfiguration, &QPushButton::clicked, this, &MainWindowNew::onAnyLeftTabBarButtonClicked);
    connect(ui->pbMainMenuBarVisualization, &QPushButton::clicked, this, &MainWindowNew::onAnyLeftTabBarButtonClicked);
    connect(ui->pbMainMenuBarHistory,       &QPushButton::clicked, this, &MainWindowNew::onAnyLeftTabBarButtonClicked);
    connect(ui->pbMainMenuBarSeriveOfBms,   &QPushButton::clicked, this, &MainWindowNew::onAnyLeftTabBarButtonClicked);
    connect(ui->pbMainMenuBarSettingsExtra, &QPushButton::clicked, this, &MainWindowNew::onAnyLeftTabBarButtonClicked);
    connect(ui->pbMainMenuBarExit,          &QPushButton::clicked, this, &MainWindowNew::onAnyLeftTabBarButtonClicked);
    m_currentPageIndex = AkbMonitor;
    m_prevPageIndex = AkbMonitor;


    //connect(ui->pbMainMenuBarVisualization, &QPushButton::clicked, ui->tabVisualization, &VisualizationPage::onVisualizationPageSelected);

    initAnimationForLeftTabsBar();

    connect(ui->pbMainMenuBarHideMenu, &QPushButton::clicked, this, &MainWindowNew::onShrink);

    //connect(m_btnGroupMainMenuBar, QOverload<QAbstractButton *>::of(&QButtonGroup::buttonClicked), this, &MainWindowNew::onMainMenuBarButtonClicked);

    //onHideAndShowConnectWindowAgain();

    connect(ui->tabConfiguration, &ConfigurationPage::sendMessage, ui->tabSeriveOfBms, &BmsServicePage::printReceived);

    //connect(ui->pbMainMenuBarExit, &QPushButton::clicked, this, [=]() { QApplication::quit(); } );
    connect(ui->tabConnect, &ConnectAndEnterPage::sigConnected, this, &MainWindowNew::onHideConnectWindow );
    connect(ui->tabConnect, &ConnectAndEnterPage::sigReject, this, [=]() { QApplication::quit(); } );
    connect(ui->pbMainMenuBarExit, &QPushButton::clicked, this, &MainWindowNew::onShowConnectWindow);
    //connect(this, &MainWindowNew::sigShowConnectWindow, this, &MainWindowNew::onShowConnectWindow);

    //prepareWindowBeforeShow


    //* // ENABLE WHEN FINISHED
    connect(this, &MainWindowNew::loadParams, ui->tabAkbMonitor, &AkbMonitorPage::onLoadParams);
    connect(this, &MainWindowNew::loadParams, ui->tabConfiguration, &ConfigurationPage::loadParams);
    //*/

    //if(mSerialPort->isOpen()) {


    //emit sigShowConnectWindow();
    onShowConnectWindow();

    ///mPageDebugPrint->printConsole("DieBieMSTool " + mVersion + " started<br>");


    /////////////////////////////////////////////////////
    /// mainwnidow
    ///

    QLoggingCategory::setFilterRules("qt.network.ssl.warning=false");

    mVersion        = QString::number(DT_VERSION);
    mDieBieMS       = new BMSInterface(this);
    mStatusInfoTime = 0;
    mStatusLabelText = "";
    ///mStatusLabel    = new QLabel(this);
    ///ui->statusBar->addPermanentWidget(mStatusLabel);
    mTimer      = new QTimer(this);
    mKeyLeft    = false;
    mKeyRight   = false;
    mMcConfRead = false;
    mDieBieMS->bmsConfig()->loadParamsXml("://res/config.xml");
    mDieBieMS->infoConfig()->loadParamsXml("://res/info.xml");

    reloadPages();

    qInstallMessageHandler(myMessageOutput);

    connect(mTimer, &QTimer::timeout, this, &MainWindowNew::timerSlot);
    connect(mDieBieMS, &BMSInterface::statusMessage, this, &MainWindowNew::showStatusInfo);
    connect(mDieBieMS, &BMSInterface::messageDialog, this, &MainWindowNew::showMessageDialog);
    connect(mDieBieMS, &BMSInterface::serialPortNotWritable, this, &MainWindowNew::serialPortNotWritable);
    connect(mDieBieMS->commands(), &Commands::bmsConfigCheckResult, this, &MainWindowNew::bmsConfigCheckResult);
    connect(mDieBieMS->bmsConfig(), &ConfigParams::updated, this, &MainWindowNew::bmsconfUpdated);
    ///connect(ui->actionAboutQt, SIGNAL(triggered(bool)), qApp, SLOT(aboutQt()));

    // init everything for Real time watching and updating info

    connect(ui->tabSettingsExtra, &SettingsExtraPage::connected, this, [=]() {
        const QString greenStyle = "color: #009352; \
                background-color: #009352; \
                border-color: #009352; \
                border-width: 0px; \
                border-style: solid; \
                border-radius: 10px;";

                ui->lbHeaderConnectionIndicator->setStyleSheet(greenStyle);
    } );

    connect(ui->tabSettingsExtra, &SettingsExtraPage::disconnected, this, [=]() {
        const QString redStyle = "color: red; \
                        background-color: red; \
                        border-color: red; \
                        border-width: 0px; \
                        border-style: solid; \
                        border-radius: 10px;";

        ui->lbHeaderConnectionIndicator->setStyleSheet(redStyle);
    } );

    //connect(this, &MainWindowNew::loadParams, ui->tabConfiguration, &ConfigurationPage::loadParams);

    /*
    connect(mTimer, SIGNAL(timeout()), this, SLOT(timerSlot()));
    connect(mDieBieMS, SIGNAL(statusMessage(QString, bool)), this, SLOT(showStatusInfo(QString, bool)));
    connect(mDieBieMS, SIGNAL(messageDialog(QString, QString, bool, bool)), this,
            SLOT(showMessageDialog(QString, QString, bool, bool)));
    connect(mDieBieMS, SIGNAL(serialPortNotWritable(QString)), this, SLOT(serialPortNotWritable(QString)));
    connect(mDieBieMS->commands(), SIGNAL(bmsConfigCheckResult(QStringList)), this,
            SLOT(bmsConfigCheckResult(QStringList)));
    ///connect(ui->actionAboutQt, SIGNAL(triggered(bool)), qApp, SLOT(aboutQt()));
    */

    // Remove the menu with the option to hide the toolbar
    ///ui->mainToolBar->setContextMenuPolicy(Qt::PreventContextMenu);


    // Restore size and position
    if (mSettings.contains("MainWindowNew/size")) {
        resize(mSettings.value("MainWindowNew/size").toSize());
    }

    if (mSettings.contains("MainWindowNew/position")) {
        move(mSettings.value("MainWindowNew/position").toPoint());
    }

    if (mSettings.contains("MainWindowNew/maximized")) {
        bool maximized = mSettings.value("MainWindowNew/maximized").toBool();
        if (maximized) {
            showMaximized();
        }
    }


    mTimer->start(20);

    mPageDebugPrint->printConsole("DieBieMSTool " + mVersion + " started<br>");
}
//*/

void MainWindowNew::onAnyLeftTabBarButtonClicked()
{
    bool isOtherPageClicked = (m_prevPageIndex != m_currentPageIndex);

    bool isBtn = false;
    QPushButton* _sender = (QPushButton*)sender();

    if( _sender == ui->pbMainMenuBarAkbMonitor)         { isBtn = true; m_currentPageIndex = AkbMonitor;    }
    else if(_sender == ui->pbMainMenuBarCellsMonitor  ) { isBtn = true; m_currentPageIndex = CellsMonitor;  }
    else if(_sender == ui->pbMainMenuBarConfiguration ) { isBtn = true; m_currentPageIndex = Configuration; }
    else if(_sender == ui->pbMainMenuBarVisualization ) { isBtn = true; m_currentPageIndex = Visualization; }
    else if(_sender == ui->pbMainMenuBarHistory       ) { isBtn = true; m_currentPageIndex = History;       }
    else if(_sender == ui->pbMainMenuBarSeriveOfBms   ) { isBtn = true; m_currentPageIndex = SeriveOfBms;   }
    else if(_sender == ui->pbMainMenuBarSettingsExtra ) { isBtn = true; m_currentPageIndex = SettingsExtra; }
    else if(_sender == ui->pbMainMenuBarExit          ) { isBtn = true; m_currentPageIndex = ConnectWindow; }

    if(!isBtn)
        return;

    unselectAllLeftTabBarButtons();
    selectCurrentLeftTabBarButton();

    ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex);


    switch(m_currentPageIndex)
    {
    case AkbMonitor:
    case CellsMonitor:
    case Configuration:
    case History:
    case SeriveOfBms:
    case SettingsExtra:
    case ConnectWindow:
         ui->tabVisualization->setIsPageActivated(false);
        break;

    case Visualization:
         ui->tabVisualization->setIsPageActivated(true);
        break;
    }

    m_prevPageIndex = m_currentPageIndex;

    /*
    connect(ui->pbMainMenuBarAkbMonitor,    &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = AkbMonitor;    selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarCellsMonitor,  &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = CellsMonitor;  selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarConfiguration, &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = Configuration; selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarVisualization, &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = Visualization; selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarHistory,       &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = History;       selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarSeriveOfBms,   &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = SeriveOfBms;   selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarSettingsExtra, &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = SettingsExtra; selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarExit,          &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = ConnectWindow; selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    */
}

/*
MainWindowNew::MainWindowNew(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindowNew),
    m_currentPageIndex(TabWidgetPage::ConnectWindow)
{
    ui->setupUi(this);

    ui->pbMainMenuBarHideMenu->hide();
    ui->mStatusLabel->hide();

    QLoggingCategory::setFilterRules("qt.network.ssl.warning=false");

    mVersion = QString::number(DT_VERSION);

    //this->setAttribute(Qt::WA_DeleteOnClose);

    initDieBieMs();

    setWindowFlags(Qt::CustomizeWindowHint);
    setFixedSize(mWidth,mHeight);

    m_minimize = false;
    ui->lbHeaderSerialNumberName->setFont(QFont(("Segoe WP SemiLight"), (m_minimize ? 12 : 9) ));
    //ui->lbHeaderSerialNumberName->setVisible(!m_minimize);
    //ui->lbHeaderSerialNumberNameMini->setVisible(!ui->lbHeaderSerialNumberName->isVisible());

    ui->pbMainMenuBarHideMenu     ->setIconStringForButton(":/res/b0L.png");
    ui->pbMainMenuBarAkbMonitor   ->setIconStringForButton(":/res/menu-akb-monitor.png");
    ui->pbMainMenuBarCellsMonitor ->setIconStringForButton(":/res/menu-cells-monitor.png");
    ui->pbMainMenuBarConfiguration->setIconStringForButton(":/res/menu-configuration.png");
    ui->pbMainMenuBarVisualization->setIconStringForButton(":/res/menu-visualization.png");
    ui->pbMainMenuBarHistory      ->setIconStringForButton(":/res/menu-history.png");
    ui->pbMainMenuBarSeriveOfBms  ->setIconStringForButton(":/res/menu-serive-of-bms.png");
    ui->pbMainMenuBarSettingsExtra->setIconStringForButton(":/res/menu-settings-extra.png");
    ui->pbMainMenuBarExit         ->setIconStringForButton(":/res/menu-exit.png");


    connect(ui->pbMainMenuBarAkbMonitor,    &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = AkbMonitor;    selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarCellsMonitor,  &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = CellsMonitor;  selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarConfiguration, &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = Configuration; selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarVisualization, &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = Visualization; selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarHistory,       &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = History;       selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarSeriveOfBms,   &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = SeriveOfBms;   selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarSettingsExtra, &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = SettingsExtra; selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );
    connect(ui->pbMainMenuBarExit,          &QPushButton::clicked, this, [=]() { unselectAllLeftTabBarButtons(); m_currentPageIndex = ConnectWindow; selectCurrentLeftTabBarButton(); ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex); } );

    //connect(ui->pbMainMenuBarVisualization, &QPushButton::clicked, ui->tabVisualization, &VisualizationPage::onVisualizationPageSelected);

    initAnimationForLeftTabsBar();

    connect(ui->pbMainMenuBarHideMenu, &QPushButton::clicked, this, &MainWindowNew::onShrink);

    //connect(m_btnGroupMainMenuBar, QOverload<QAbstractButton *>::of(&QButtonGroup::buttonClicked), this, &MainWindowNew::onMainMenuBarButtonClicked);

    //onHideAndShowConnectWindowAgain();

    connect(ui->tabConfiguration, &ConfigurationPage::sendMessage, ui->tabSeriveOfBms, &BmsServicePage::printReceived);

    //connect(ui->pbMainMenuBarExit, &QPushButton::clicked, this, [=]() { QApplication::quit(); } );
    connect(ui->tabConnect, &ConnectAndEnterPage::sigConnected, this, &MainWindowNew::onHideConnectWindow );
    connect(ui->tabConnect, &ConnectAndEnterPage::sigReject, this, [=]() { QApplication::quit(); } );
    connect(ui->pbMainMenuBarExit, &QPushButton::clicked, this, &MainWindowNew::onShowConnectWindow);
    //connect(this, &MainWindowNew::sigShowConnectWindow, this, &MainWindowNew::onShowConnectWindow);

    //prepareWindowBeforeShow




    //if(mSerialPort->isOpen()) {


    //emit sigShowConnectWindow();
    onShowConnectWindow();

    mPageDebugPrint->printConsole("DieBieMSTool " + mVersion + " started<br>");
}
*/

MainWindowNew::~MainWindowNew()
{
    // Save settings
    mSettings.setValue("version", mVersion);
    mSettings.setValue("MainWindowNew/position", pos());
    mSettings.setValue("MainWindowNew/maximized", isMaximized());

    if (!isMaximized()) {
        mSettings.setValue("MainWindowNew/size", size());
    }

    delete ui;
}

/////////////////////////////////////////////////////////////


void MainWindowNew::onShrink()
{
    if (m_minimize) {
        clearAllBtnsText();
        m_animgroupMin->start();
        ui->pbMainMenuBarHideMenu->setIconStringForButton(":/res/b0R.png");
        ui->lbHeaderSerialNumberName->setFont(QFont(("Segoe WP SemiLight"), 12 ));
    }
    else {
        restoreAllBtnsText();
        m_animgroupMax->start();
        ui->pbMainMenuBarHideMenu->setIconStringForButton(":/res/b0L.png");
        ui->lbHeaderSerialNumberName->setFont(QFont(("Segoe WP SemiLight"), 9) );
    }

    m_minimize = !m_minimize;
}


void MainWindowNew::clearAllBtnsText()
{
    //clearBtnText();
    clearBtnText( ui->pbMainMenuBarHideMenu       );
    clearBtnText( ui->pbMainMenuBarAkbMonitor     );
    clearBtnText( ui->pbMainMenuBarCellsMonitor   );
    clearBtnText( ui->pbMainMenuBarConfiguration  );
    clearBtnText( ui->pbMainMenuBarVisualization  );
    clearBtnText( ui->pbMainMenuBarHistory        );
    clearBtnText( ui->pbMainMenuBarSeriveOfBms    );
    clearBtnText( ui->pbMainMenuBarSettingsExtra    );
    clearBtnText( ui->pbMainMenuBarExit           );
}
void MainWindowNew::restoreAllBtnsText()
{
    restoreBtnText( ui->pbMainMenuBarHideMenu       );
    restoreBtnText( ui->pbMainMenuBarAkbMonitor     );
    restoreBtnText( ui->pbMainMenuBarCellsMonitor   );
    restoreBtnText( ui->pbMainMenuBarConfiguration  );
    restoreBtnText( ui->pbMainMenuBarVisualization  );
    restoreBtnText( ui->pbMainMenuBarHistory        );
    restoreBtnText( ui->pbMainMenuBarSeriveOfBms    );
    restoreBtnText( ui->pbMainMenuBarSettingsExtra    );
    restoreBtnText( ui->pbMainMenuBarExit           );
}

void MainWindowNew::clearBtnText(CustomLeftTabBarButton *btn)
{
    btn->setProperty("tmp", btn->text());
    btn->setText("");
}
void MainWindowNew::restoreBtnText(CustomLeftTabBarButton *btn)
{
    btn->setText(btn->property("tmp").toString());
}




void MainWindowNew::setAnimLogoMin(QParallelAnimationGroup *group, QPropertyAnimation *a, int sec, QLabel *obj)
{
    a->setDuration(sec);
    QRect rec = obj->geometry();
    a->setStartValue(QRect(rec.x(), rec.y(), rec.width(), rec.height()));
    a->setEndValue(QRect(rec.x()-m_logoWay, rec.y()/2, rec.width(), rec.height()));
    a->setEasingCurve(QEasingCurve::Linear);
    group->addAnimation(a);
}
void MainWindowNew::setAnimLogoMax(QParallelAnimationGroup *group, QPropertyAnimation *a, int sec, QLabel *obj)
{
    a->setDuration(sec);
    QRect rec = obj->geometry();
    a->setStartValue(QRect(rec.x()-m_logoWay, rec.y()/2, rec.width(), rec.height()));
    a->setEndValue(QRect(rec.x(), rec.y(), rec.width(), rec.height()));
    a->setEasingCurve(QEasingCurve::Linear);
    group->addAnimation(a);
}

void MainWindowNew::setAnimParamsMin(QParallelAnimationGroup *group, QPropertyAnimation *a, int sec, QLabel *obj)
{
    a->setDuration(sec);
    QRect rec = obj->geometry();
    a->setStartValue(QRect(rec.x(), rec.y(), rec.width(), rec.height()));
    a->setEndValue(QRect(rec.x(), rec.y(), rec.width()/2, rec.height()));
    a->setEasingCurve(QEasingCurve::Linear);
    group->addAnimation(a);
}
void MainWindowNew::setAnimParamsMax(QParallelAnimationGroup *group, QPropertyAnimation *a, int sec, QLabel *obj)
{
    a->setDuration(sec);
    QRect rec = obj->geometry();
    a->setStartValue(QRect(rec.x(), rec.y(), rec.width()/2, rec.height()));
    a->setEndValue(QRect(rec.x(), rec.y(), rec.width(), rec.height()));
    a->setEasingCurve(QEasingCurve::Linear);
    group->addAnimation(a);
}

void MainWindowNew::setAnimParamsMin(QParallelAnimationGroup *group, QPropertyAnimation *a, int sec, CustomLeftTabBarButton *btn)
{
    a->setDuration(sec);
    QRect rec = btn->geometry();
    a->setStartValue(QRect(rec.x(), rec.y(), rec.width(), rec.height()));
    a->setEndValue(QRect(rec.x(), rec.y(), rec.width()/2, rec.height()));
    a->setEasingCurve(QEasingCurve::Linear);
    group->addAnimation(a);
}
void MainWindowNew::setAnimParamsMax(QParallelAnimationGroup *group, QPropertyAnimation *a, int sec, CustomLeftTabBarButton *btn)
{
    a->setDuration(sec);
    QRect rec = btn->geometry();
    a->setStartValue(QRect(rec.x(), rec.y(), rec.width()/2, rec.height()));
    a->setEndValue(QRect(rec.x(), rec.y(), rec.width(), rec.height()));
    a->setEasingCurve(QEasingCurve::Linear);
    group->addAnimation(a);
}


void MainWindowNew::initAnimationForLeftTabsBar()
{
    m_logoWay      = 65;
    int sec        = 1000;
    int min        = 100;
    int max        = 281;
    int fromShrink = max;
    int toShrink   = min;
    int fromMax    = min;
    int toMax      = max;

    m_minimize = true;
    m_animgroupMin = new QParallelAnimationGroup;
    m_animgroupMax = new QParallelAnimationGroup;

    QPropertyAnimation *aminL = new QPropertyAnimation(ui->lbIconLogo, "geometry");
    QPropertyAnimation *aminB = new QPropertyAnimation(ui->labLeftTabListBackground, "geometry");
    QPropertyAnimation *amin0 = new QPropertyAnimation(ui->pbMainMenuBarHideMenu     , "geometry");
    QPropertyAnimation *amin1 = new QPropertyAnimation(ui->pbMainMenuBarAkbMonitor   , "geometry");
    QPropertyAnimation *amin2 = new QPropertyAnimation(ui->pbMainMenuBarCellsMonitor , "geometry");
    QPropertyAnimation *amin3 = new QPropertyAnimation(ui->pbMainMenuBarConfiguration, "geometry");
    QPropertyAnimation *amin4 = new QPropertyAnimation(ui->pbMainMenuBarVisualization, "geometry");
    QPropertyAnimation *amin5 = new QPropertyAnimation(ui->pbMainMenuBarHistory      , "geometry");
    QPropertyAnimation *amin6 = new QPropertyAnimation(ui->pbMainMenuBarSeriveOfBms  , "geometry");
    QPropertyAnimation *amin7 = new QPropertyAnimation(ui->pbMainMenuBarSettingsExtra  , "geometry");
    QPropertyAnimation *amin8 = new QPropertyAnimation(ui->pbMainMenuBarExit         , "geometry");
    QPropertyAnimation *amin9 = new QPropertyAnimation(ui->mStatusLabel         , "geometry");


    QPropertyAnimation *amaxL = new QPropertyAnimation(ui->lbIconLogo, "geometry");
    QPropertyAnimation *amaxB = new QPropertyAnimation(ui->labLeftTabListBackground, "geometry");
    QPropertyAnimation *amax0 = new QPropertyAnimation(ui->pbMainMenuBarHideMenu     , "geometry");
    QPropertyAnimation *amax1 = new QPropertyAnimation(ui->pbMainMenuBarAkbMonitor   , "geometry");
    QPropertyAnimation *amax2 = new QPropertyAnimation(ui->pbMainMenuBarCellsMonitor , "geometry");
    QPropertyAnimation *amax3 = new QPropertyAnimation(ui->pbMainMenuBarConfiguration, "geometry");
    QPropertyAnimation *amax4 = new QPropertyAnimation(ui->pbMainMenuBarVisualization, "geometry");
    QPropertyAnimation *amax5 = new QPropertyAnimation(ui->pbMainMenuBarHistory      , "geometry");
    QPropertyAnimation *amax6 = new QPropertyAnimation(ui->pbMainMenuBarSeriveOfBms  , "geometry");
    QPropertyAnimation *amax7 = new QPropertyAnimation(ui->pbMainMenuBarSettingsExtra  , "geometry");
    QPropertyAnimation *amax8 = new QPropertyAnimation(ui->pbMainMenuBarExit         , "geometry");
    QPropertyAnimation *amax9 = new QPropertyAnimation(ui->mStatusLabel         , "geometry");

    setAnimLogoMin  ( m_animgroupMin, aminL, sec, ui->lbIconLogo );
    setAnimParamsMin( m_animgroupMin, aminB, sec, ui->labLeftTabListBackground );
    setAnimParamsMin( m_animgroupMin, amin0, sec, ui->pbMainMenuBarHideMenu      );
    setAnimParamsMin( m_animgroupMin, amin1, sec, ui->pbMainMenuBarAkbMonitor    );
    setAnimParamsMin( m_animgroupMin, amin2, sec, ui->pbMainMenuBarCellsMonitor  );
    setAnimParamsMin( m_animgroupMin, amin3, sec, ui->pbMainMenuBarConfiguration );
    setAnimParamsMin( m_animgroupMin, amin4, sec, ui->pbMainMenuBarVisualization );
    setAnimParamsMin( m_animgroupMin, amin5, sec, ui->pbMainMenuBarHistory       );
    setAnimParamsMin( m_animgroupMin, amin6, sec, ui->pbMainMenuBarSeriveOfBms   );
    setAnimParamsMin( m_animgroupMin, amin7, sec, ui->pbMainMenuBarSettingsExtra   );
    setAnimParamsMin( m_animgroupMin, amin8, sec, ui->pbMainMenuBarExit          );
    setAnimParamsMin( m_animgroupMin, amin9, sec, ui->mStatusLabel          );

    setAnimLogoMax  ( m_animgroupMax, amaxL, sec, ui->lbIconLogo );
    setAnimParamsMax( m_animgroupMax, amaxB, sec, ui->labLeftTabListBackground );
    setAnimParamsMax( m_animgroupMax, amax0, sec, ui->pbMainMenuBarHideMenu      );
    setAnimParamsMax( m_animgroupMax, amax1, sec, ui->pbMainMenuBarAkbMonitor    );
    setAnimParamsMax( m_animgroupMax, amax2, sec, ui->pbMainMenuBarCellsMonitor  );
    setAnimParamsMax( m_animgroupMax, amax3, sec, ui->pbMainMenuBarConfiguration );
    setAnimParamsMax( m_animgroupMax, amax4, sec, ui->pbMainMenuBarVisualization );
    setAnimParamsMax( m_animgroupMax, amax5, sec, ui->pbMainMenuBarHistory       );
    setAnimParamsMax( m_animgroupMax, amax6, sec, ui->pbMainMenuBarSeriveOfBms   );
    setAnimParamsMax( m_animgroupMax, amax7, sec, ui->pbMainMenuBarSettingsExtra   );
    setAnimParamsMax( m_animgroupMax, amax8, sec, ui->pbMainMenuBarExit          );
    setAnimParamsMax( m_animgroupMax, amax9, sec, ui->mStatusLabel          );

    //connect(ui->pushButton_13, &QPushButton::clicked, this, &MainWindowNew::onShrink);
}


void MainWindowNew::onShowConnectWindow()
{
    setAppSizeForConnectionPage();
    moveApplicationToTheCenter();

    mIsConnectionPrepared = false;
    mComPortToConnect.clear();

    setAllMainMenuBarButtonsVisible(false);
    unselectAllLeftTabBarButtons();

    m_currentPageIndex = TabWidgetPage::ConnectWindow;
    ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex);

    ui->tabWidgetPagesContent->setGeometry(0, -10, mWidth, 751);

    ui->tabConnect->prepareWindowBeforeShow();
    setLeftTopWidgetsVisible(false);
}

void MainWindowNew::onHideConnectWindow()
{
    setAppSizeForFullView();
    moveApplicationToTheCenter();

    mIsConnectionPrepared = ui->tabConnect->isConnectionPrepared();
    mComPortToConnect     = ui->tabConnect->portToConnect();

    m_currentPageIndex = TabWidgetPage::AkbMonitor;
    ui->tabWidgetPagesContent->setCurrentIndex(m_currentPageIndex);

    setAllMainMenuBarButtonsVisible(true);
    selectCurrentLeftTabBarButton();

    ui->tabWidgetPagesContent->setGeometry(280, -10, 1084, 751);

    setLeftTopWidgetsVisible(true);
    emit loadParams();
}


void MainWindowNew::setLeftTopWidgetsVisible(bool value)
{
    ui->lbHeaderConnectionName      ->setVisible(value);
    ui->lbHeaderConnectionIndicator ->setVisible(value);
    ui->lbHeaderBmsVersion          ->setVisible(value);
    ui->lbHeaderSerialNumberName    ->setVisible(value);
    ui->lbHeaderSerialNumberValue   ->setVisible(value);
    ui->labHeaderSeparator          ->setVisible(value);
    ui->lbHeaderLanguageName        ->setVisible(value);
    ui->lbHeaderLanguageIcon        ->setVisible(value);
}

void MainWindowNew::setAllMainMenuBarButtonsVisible(bool val)
{
    ui->pbMainMenuBarAkbMonitor   ->setVisible(val);
    ui->pbMainMenuBarCellsMonitor ->setVisible(val);
    ui->pbMainMenuBarConfiguration->setVisible(val);
    ui->pbMainMenuBarVisualization->setVisible(val);
    ui->pbMainMenuBarHistory      ->setVisible(val);
    ui->pbMainMenuBarSeriveOfBms  ->setVisible(val);
    ui->pbMainMenuBarSettingsExtra->setVisible(val);
    ui->pbMainMenuBarExit         ->setVisible(val);
}

void MainWindowNew::unselectAllLeftTabBarButtons()
{
    ui->pbMainMenuBarAkbMonitor   ->setChecked(false);
    ui->pbMainMenuBarCellsMonitor ->setChecked(false);
    ui->pbMainMenuBarConfiguration->setChecked(false);
    ui->pbMainMenuBarVisualization->setChecked(false);
    ui->pbMainMenuBarHistory      ->setChecked(false);
    ui->pbMainMenuBarSeriveOfBms  ->setChecked(false);
    ui->pbMainMenuBarSettingsExtra->setChecked(false);
    ui->pbMainMenuBarExit         ->setChecked(false);
}

void MainWindowNew::selectCurrentLeftTabBarButton()
{
    switch (m_currentPageIndex) {
    case AkbMonitor   : ui->pbMainMenuBarAkbMonitor   ->setChecked(true); break;
    case CellsMonitor : ui->pbMainMenuBarCellsMonitor ->setChecked(true); break;
    case Configuration: ui->pbMainMenuBarConfiguration->setChecked(true); break;
    case Visualization: ui->pbMainMenuBarVisualization->setChecked(true); break;
    case History      : ui->pbMainMenuBarHistory      ->setChecked(true); break;
    case SeriveOfBms  : ui->pbMainMenuBarSeriveOfBms  ->setChecked(true); break;
    case SettingsExtra: ui->pbMainMenuBarSettingsExtra->setChecked(true); break;
    //case Exit       : ui->pbMainMenuBarExit         ->setChecked(true); break;
    case ConnectWindow: break;
    };
}

/////////////////////////////////////////////////////////////

void MainWindowNew::timerSlot()
{
    // Update status label
    if (mStatusInfoTime)
    {
        mStatusInfoTime--;
        if (!mStatusInfoTime)
        {
///            mStatusLabel->setStyleSheet(qApp->styleSheet());
                emit sendStatusLabelStyleSheet(qApp->styleSheet());
        }
    }
    else
    {
        QString str = mDieBieMS->getConnectedPortName();
///     if (str != mStatusLabel->text())
        if(str != mStatusLabelText)
        {
///            mStatusLabel->setText(mDieBieMS->getConnectedPortName());
                mStatusLabelText = mDieBieMS->getConnectedPortName();
            static QString statusLast = "";

            if (str != statusLast)
            {
                mPageDebugPrint->printConsole("Status: " + str + "<br>");
                statusLast = str;
            }
        }
    }

    // CAN fwd
    //if (ui->actionCanFwd->isChecked() != mDieBieMS->commands()->getSendCan()) {
    //    ui->actionCanFwd->setChecked(mDieBieMS->commands()->getSendCan());
    //}

    // RT data only every 5 iterations
    //if (ui->actionRtData->isChecked())
    {
        static int values_cnt = 0;
        static int cells_cnt  = 0;

        values_cnt++;
        if (values_cnt >= 5) {
            values_cnt = 0;
            mDieBieMS->commands()->getValues();
        }

        cells_cnt++;
        if (cells_cnt >= 20) {
            cells_cnt = 0;
            mDieBieMS->commands()->getCells();
        }
    }

    // Send alive command once every 10 iterations
    //if (ui->actionSendAlive->isChecked())
    {
        static int alive_cnt = 0;
        alive_cnt++;
        if (alive_cnt >= 10) {
            alive_cnt = 0;
            mDieBieMS->commands()->sendAlive();
        }
    }

    // Read configuration it isn't read since starting VESC Tool
    //if (mDieBieMS->isPortConnected())
    {
        static int conf_cnt = 0;
        conf_cnt++;
        if (conf_cnt >= 20) {
            conf_cnt = 0;
            if (!mMcConfRead) {
                mDieBieMS->commands()->getBMSconf();
            }
        }
    }

    // Disable all data streaming when uploading firmware
    //if (mDieBieMS->commands()->getFirmwareUploadProgress() > 0.1)
    {
///        ui->actionSendAlive->setChecked(false);
///        ui->actionRtData->setChecked(false);
    }

    // Run startup checks
    static bool has_run_start_checks = false;
    /*//if (!has_run_start_checks)
    {
        has_run_start_checks = true;
        checkUdev();
        Utility::checkVersion(mDieBieMS);
    }
    */
}

void MainWindowNew::showStatusInfo(QString info, bool isGood)
{
    if (isGood) {
///        mStatusLabel->setStyleSheet("QLabel { background-color : lightgreen; color : black; }");
        emit sendStatusLabelStyleSheet("QLabel { background-color : lightgreen; color : black; }");
        mPageDebugPrint->printConsole("Status: " + info + "<br>");
    }
    else
    {
///        mStatusLabel->setStyleSheet("QLabel { background-color : red; color : black; }");
        emit sendStatusLabelStyleSheet("QLabel { background-color : red; color : black; }");
        mPageDebugPrint->printConsole("<font color=\"red\">Status: " + info + "</font><br>");
    }

    mStatusInfoTime = 80;
///    mStatusLabel->setText(info);
    mStatusLabelText = info;
}

void MainWindowNew::showMessageDialog(const QString &title, const QString &msg, bool isGood, bool richText)
{
    (void)richText;

    if (isGood)
    {
        QMessageBox::information(this, title, msg);
    }
    else
    {
        QMessageBox::warning(this, title, msg);
    }
}

void MainWindowNew::serialPortNotWritable(const QString &port)
{
    (void)port;
/*
#ifdef Q_OS_LINUX
    QMessageBox::StandardButton reply;
    reply = QMessageBox::warning(this, tr("Connect Serial Port"),
                                 tr("The serial port is not writable. This can usually be fixed by "
                                    "adding your user to the dialout, uucp and/or lock groups. Would "
                                    "you like to do that?"),
                                 QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);

    if (reply == QMessageBox::Yes) {
        QString name = qgetenv("USER");
        if (name.isEmpty()) {
            name = qgetenv("USERNAME");
        }

        bool hasDialout = !runCmd("getent",
                                  QStringList() << "group"
                                                << "dialout")
                                   .isEmpty();
        bool hasUucp = !runCmd("getent",
                               QStringList() << "group"
                                             << "uucp")
                                .isEmpty();
        bool hasLock = !runCmd("getent",
                               QStringList() << "group"
                                             << "lock")
                                .isEmpty();

        QString grps;
        if (hasDialout) {
            grps += "dialout";
        }

        if (hasUucp) {
            if (!grps.isEmpty()) {
                grps += ",";
            }
            grps += "uucp";
        }

        if (hasLock) {
            if (!grps.isEmpty()) {
                grps += ",";
            }
            grps += "lock";
        }

        QProcess process;
        process.setEnvironment(QProcess::systemEnvironment());
        process.start("pkexec",
                      QStringList() << "usermod"
                                    << "-aG" << grps << name);
        waitProcess(process);
        if (process.exitCode() == 0) {
            showMessageDialog(tr("Command Result"),
                              tr("Result from command:\n\n"
                                 "%1\n"
                                 "You have to reboot for this "
                                 "change to take effect.")
                                      .arg(QString(process.readAllStandardOutput())),
                              true, false);
        } else {
            showMessageDialog(tr("Command Result"), tr("Running command failed."), false, false);
        }
        process.close();
    }
#endif
*/
}

void MainWindowNew::bmsconfUpdated()
{
    mMcConfRead = true;

    // Серийный номер * //ui->editSerialNumber
    getSerialNumber(ui->lbHeaderSerialNumberValue , mDieBieMS->bmsConfig(), "notUsedCurrentThreshold");
}

void MainWindowNew::bmsConfigCheckResult(QStringList paramsNotSet)
{
    if (!paramsNotSet.isEmpty()) {
        ParamDialog::showParams(tr("Parameters truncated"),
                                tr("The following parameters were truncated because they were set outside "
                                   "of their allowed limits."),
                                mDieBieMS->bmsConfig(), paramsNotSet, this);
    }
}

/*
void MainWindowNew::on_actionReconnect_triggered()
{
    mDieBieMS->reconnectLastPort();
}

void MainWindowNew::on_actionDisconnect_triggered()
{
    mDieBieMS->disconnectPort();
}

void MainWindowNew::on_actionReboot_triggered()
{
    mDieBieMS->commands()->reboot();
}

void MainWindowNew::on_actionReadBMScconf_triggered()
{
    mDieBieMS->commands()->getBMSconf();
}

void MainWindowNew::on_actionReadBMScconfDefault_triggered()
{
    mDieBieMS->commands()->getBMSconfDefault();
}

void MainWindowNew::on_actionWriteBMScconf_triggered()
{
    mDieBieMS->commands()->setBMSconf();
}

void MainWindowNew::on_actionSaveBMSConfXml_triggered()
{
    QString path;
    path = QFileDialog::getSaveFileName(this, tr("Choose where to save the motor configuration XML file"), ".",
                                        tr("Xml files (*.xml)"));

    if (path.isNull()) {
        return;
    }

    if (!path.toLower().endsWith(".xml")) {
        path += ".xml";
    }

    bool res = mDieBieMS->bmsConfig()->saveXml(path, "bmsConfiguration");

    if (res) {
        showStatusInfo("Saved motor configuration", true);
    } else {
        showMessageDialog(tr("Save motor configuration"),
                          tr("Could not save motor configuration:<BR>"
                             "%1")
                                  .arg(mDieBieMS->bmsConfig()->xmlStatus()),
                          false, false);
    }
}


void MainWindowNew::on_actionLoadBMSConfXml_triggered()
{
    QString path;
    path = QFileDialog::getOpenFileName(this, tr("Choose motor configuration file to load"), ".",
                                        tr("Xml files (*.xml)"));

    if (path.isNull()) {
        return;
    }

    bool res = mDieBieMS->bmsConfig()->loadXml(path, "bmsConfiguration");

    if (res) {
        showStatusInfo("Loaded motor configuration", true);
    } else {
        showMessageDialog(tr("Load motor configuration"),
                          tr("Could not load motor configuration:<BR>"
                             "%1")
                                  .arg(mDieBieMS->bmsConfig()->xmlStatus()),
                          false, false);
    }
}


void MainWindowNew::on_actionExit_triggered()
{
    qApp->exit();
}

void MainWindowNew::on_actionAbout_triggered()
{
    QMessageBox::about(this, "ENNOID-BMS Tool", Utility::aboutText());
}

void MainWindowNew::on_actionLibrariesUsed_triggered()
{
    QMessageBox::about(this, "Libraries Used",
                       tr("<b>Icons<br>"
                          "<a href=\"https://icons8.com/\">https://icons8.com/</a><br><br>"
                          "<b>Plotting<br>"
                          "<a href=\"http://qcustomplot.com/\">http://qcustomplot.com/</a>"));
}

void MainWindowNew::addPageItem(QString name, QString icon, QString groupIcon, bool bold, bool indented)
{
    QListWidgetItem *item = new QListWidgetItem();
    ui->pageList->addItem(item);
    PageListItem *li = new PageListItem(name, icon, groupIcon, this);
    li->setBold(bold);
    li->setIndented(indented);
    ui->pageList->setItemWidget(item, li);
}

void MainWindowNew::saveParamFileDialog(QString conf, bool wrapIfdef)
{
    ConfigParams *params = 0;

    if (conf.toLower() == "mcconf") {
        params = mDieBieMS->bmsConfig();
    } else {
        qWarning() << "Invalid conf" << conf;
        return;
    }

    QString path;
    path = QFileDialog::getSaveFileName(this, tr("Choose where to save the configuration header file"), ".",
                                        tr("h files (*.h)"));

    if (path.isNull()) {
        return;
    }

    if (path.contains(" ")) {
        showMessageDialog(tr("Save header"), tr("Spaces are not allowed in the filename."), false, false);
        return;
    }

    if (!path.toLower().endsWith(".h")) {
        path += ".h";
    }

    bool res = params->saveCDefines(path, wrapIfdef);

    if (res) {
        showStatusInfo("Saved C header", true);
    } else {
        showMessageDialog(tr("Save header"), tr("Could not save header"), false, false);
    }
}
*/

/*
void MainWindowNew::showPage(const QString &name)
{
    for (int i = 0; i < ui->pageList->count(); i++) {
        PageListItem *p = (PageListItem *)(ui->pageList->itemWidget(ui->pageList->item(i)));
        if (p->name() == name) {
            ui->pageList->setCurrentRow(i);
            break;
        }
    }
}
*/

void MainWindowNew::reloadPages()
{
/*    // Remove pages (if any)
    ui->pageList->clear();
    while (ui->pageWidget->count() != 0) {
        QWidget *widget = ui->pageWidget->widget(0);
        ui->pageWidget->removeWidget(widget);
        widget->deleteLater();
    }

    mPageWelcome = new PageWelcome(this);
    mPageWelcome->setDieBieMS(mDieBieMS);
    ui->pageWidget->addWidget(mPageWelcome);
    addPageItem(tr("Welcome"), "://res/icons/Home-96.png", "", true);

    mPageConnection = new PageConnection(this);
    mPageConnection->setDieBieMS(mDieBieMS);
    ui->pageWidget->addWidget(mPageConnection);
    addPageItem(tr("Connection"), "://res/icons/Connected-96.png", "", true);

    mPageFirmware = new PageFirmware(this);
    mPageFirmware->setDieBieMS(mDieBieMS);
    ui->pageWidget->addWidget(mPageFirmware);
    addPageItem(tr("Firmware"), "://res/icons/Electronics-96.png", "", true);

    mPageMasterSettings = new PageMasterSettings(this);
    mPageMasterSettings->setDieBieMS(mDieBieMS);
    ui->pageWidget->addWidget(mPageMasterSettings);
    addPageItem(tr("Master Settings"), "://res/icons/Outgoing Data-96.png", "", true);

    mPageMasterGeneral = new PageMasterGeneral(this);
    mPageMasterGeneral->setDieBieMS(mDieBieMS);
    ui->pageWidget->addWidget(mPageMasterGeneral);
    addPageItem(tr("General"), "://res/icons/Horizontal Settings Mixer-96.png", "", false, true);

    mPageMasterCell = new PageMasterCell(this);
    mPageMasterCell->setDieBieMS(mDieBieMS);
    ui->pageWidget->addWidget(mPageMasterCell);
    addPageItem(tr("Cell Management"), "://res/icons/batteries-96.png", "", false, true);

    mPageMasterSwitch = new PageMasterSwitch(this);
    mPageMasterSwitch->setDieBieMS(mDieBieMS);
    ui->pageWidget->addWidget(mPageMasterSwitch);
    addPageItem(tr("Switch"), "://res/icons/Toggle Off-96_2.png", "", false, true);

    mPageMasterSignals = new PageMasterSignals(this);
    mPageMasterSignals->setDieBieMS(mDieBieMS);
    ui->pageWidget->addWidget(mPageMasterSignals);
    addPageItem(tr("Signals"), "://res/icons/bldc.png", "", false, true);

    mPageMasterDisplay = new PageMasterDisplay(this);
    mPageMasterDisplay->setDieBieMS(mDieBieMS);
    ui->pageWidget->addWidget(mPageMasterDisplay);
    addPageItem(tr("Display"), "://res/icons/Calculator-96.png", "", false, true);

    mSlaveSettings = new PageSlaveSettings(this);
    mSlaveSettings->setDieBieMS(mDieBieMS);
    ui->pageWidget->addWidget(mSlaveSettings);
    addPageItem(tr("Slave Settings"), "://res/icons/Outgoing Data-96.png", "", true);

    mPageSlaveGeneral = new PageSlaveGeneral(this);
    mPageSlaveGeneral->setDieBieMS(mDieBieMS);
    ui->pageWidget->addWidget(mPageSlaveGeneral);
    addPageItem(tr("General"), "://res/icons/Horizontal Settings Mixer-96.png", "", false, true);

    mPageSlaveSwitch = new PageSlaveSwitch(this);
    mPageSlaveSwitch->setDieBieMS(mDieBieMS);
    ui->pageWidget->addWidget(mPageSlaveSwitch);
    addPageItem(tr("Switch"), "://res/icons/Toggle Off-96_2.png", "", false, true);

    mPageSlaveIO = new PageSlaveIO(this);
    mPageSlaveIO->setDieBieMS(mDieBieMS);
    ui->pageWidget->addWidget(mPageSlaveIO);
    addPageItem(tr("IO"), "://res/icons/Rs 232 Male-96.png", "", false, true);

    mPageSlaveFANs = new PageSlaveFAN(this);
    mPageSlaveFANs->setDieBieMS(mDieBieMS);
    ui->pageWidget->addWidget(mPageSlaveFANs);
    addPageItem(tr("FANs"), "://res/icons/fan-96.png", "", false, true);

    mPageDataAnalysis = new PageDataAnalysis(this);
    mPageDataAnalysis->setDieBieMS(mDieBieMS);
    ui->pageWidget->addWidget(mPageDataAnalysis);
    addPageItem(tr("Data Analysis"), "://res/icons/Line Chart-96.png", "", true);

    mPageRtData = new PageRtData(this);
    mPageRtData->setDieBieMS(mDieBieMS);
    ui->pageWidget->addWidget(mPageRtData);
    addPageItem(tr("Realtime Data"), "://res/icons/rt_off.png", "", false, true);

    mPageTerminal = new PageTerminal(this);
    mPageTerminal->setDieBieMS(mDieBieMS);
    ui->pageWidget->addWidget(mPageTerminal);
    addPageItem(tr("Terminal"), "://res/icons/Console-96.png", "", true);

    mPageDebugPrint = new PageDebugPrint(this);
    ui->pageWidget->addWidget(mPageDebugPrint);
    addPageItem(tr("Debug Console"), "://res/icons/Bug-96.png", "", true);

    mPageSettings = new PageSettings(this);
    ui->pageWidget->addWidget(mPageSettings);
    addPageItem(tr("Tool Settings"), "://res/icons/Settings-96.png", "", true);

    // Adjust sizes
    QFontMetrics fm(this->font());
    int          width  = fm.width("Welcome & Wizards++++++");
    int          height = fm.height();

    for (int i = 0; i < ui->pageList->count(); i++) {
        QListWidgetItem *item = ui->pageList->item(i);
        item->setSizeHint(QSize(item->sizeHint().width(), height));
    }

    ui->pageList->setMinimumWidth(width);
    ui->pageList->setMaximumWidth(width);
    ui->pageLabel->setMaximumWidth(width);
    ui->pageLabel->setMaximumHeight((394 * width) / 1549);

    ui->pageList->setCurrentRow(0);
    ui->pageWidget->setCurrentIndex(0);
*/


//}
//void MainWindowNew::initDieBieMs()
//{
    // mVersion = QString::number(DT_VERSION);
    mDieBieMS       = new BMSInterface(this);

    //void portConnectedChanged();
    //void autoConnectProgressUpdated(double progress, bool isOngoing);
    //void autoConnectFinished();

    ui->tabConnect->initDieBieMS(mDieBieMS);
    //ui->tabConnect->setDieBieMS(mDieBieMS);
    ui->tabAkbMonitor->setDieBieMS(mDieBieMS);
    ui->tabCellsMonitor->setDieBieMS(mDieBieMS);
    ui->tabConfiguration->setDieBieMS(mDieBieMS);
    ui->tabVisualization->setDieBieMS(mDieBieMS);
    ui->tabHistory->setDieBieMS(mDieBieMS);
    ui->tabSeriveOfBms->setDieBieMS(mDieBieMS);
    //ui->tabSettingsExtra->setDieBieMS(mDieBieMS);

    mPageDebugPrint = ui->tabHistory;
    ui->tabConnect->setDebugPrintPage(mPageDebugPrint);
    ui->tabConfiguration->setDebugPrintPage(mPageDebugPrint);

    // init everything for Real time watching and updating info
    mStatusInfoTime = 0;
///    ui->mStatusLabel->clear(); // = new QLabel(this);
///    ui->statusBar->addPermanentWidget(mStatusLabel);
    mStatusLabelText.clear();

    mMcConfRead = false;


    mTimer      = new QTimer(this);
    connect(mTimer, &QTimer::timeout, this, &MainWindowNew::timerSlot);
    mTimer->start(20);
    // init everything for Real time watching and updating info

    connect(ui->tabSettingsExtra, &SettingsExtraPage::connected, this, [=]() {
        const QString greenStyle = "color: lime; \
                background-color: lime; \
                border-color: lime; \
                border-width: 0px; \
                border-style: solid; \
                border-radius: 10px;";

                ui->lbHeaderConnectionIndicator->setStyleSheet(greenStyle);
    } );

    connect(ui->tabSettingsExtra, &SettingsExtraPage::disconnected, this, [=]() {
        const QString redStyle = "color: red; \
                        background-color: red; \
                        border-color: red; \
                        border-width: 0px; \
                        border-style: solid; \
                        border-radius: 10px;";

        ui->lbHeaderConnectionIndicator->setStyleSheet(redStyle);
    } );

    //connect(this, &MainWindowNew::loadParams, ui->tabConfiguration, &ConfigurationPage::loadParams);
}


void MainWindowNew::checkUdev()
{
    // Check if udev rules for modemmanager are installed
    /*#ifdef Q_OS_LINUX
        QFileInfo fi_mm("/lib/udev/rules.d/77-mm-usb-device-blacklist.rules");
        if (fi_mm.exists()) {
            QFileInfo fi_bms("/lib/udev/rules.d/45-vesc.rules");
            if (!fi_vesc.exists()) {
                QMessageBox::StandardButton reply;
                reply = QMessageBox::information(this,
                                                 tr("Modemmenager"),
                                                 tr("It looks like modemmanager is installed on your system, and that "
                                                    "there are no VESC udev rules installed. This will cause a delay "
                                                    "from when you plug in the VESC until you can use it. Would you like
    " "to add a udev rule to prevent modemmanager from grabbing the VESC?"), QMessageBox::Yes | QMessageBox::No,
    QMessageBox::Yes);

                if (reply == QMessageBox::Yes) {
                    QFile f_bms(QDir::temp().absoluteFilePath(fi_vesc.fileName()));
                    if (!f_vesc.open(QIODevice::WriteOnly | QIODevice::Text)) {
                        showMessageDialog(tr("Create File Error"),
                                          f_vesc.errorString(),
                                          false, false);
                        return;
                    }

                    f_vesc.write("# Prevent modemmanager from grabbing the VESC\n"
                                 "ATTRS{idVendor}==\"0483\", ATTRS{idProduct}==\"5740\",
    ENV{ID_MM_DEVICE_IGNORE}=\"1\"\n"); f_vesc.close();

                    QFileInfo fi_new(f_vesc);
                    QProcess process;
                    process.setEnvironment(QProcess::systemEnvironment());
                    process.start("pkexec", QStringList() <<
                                  "mv" <<
                                  fi_new.absoluteFilePath() <<
                                  fi_vesc.absolutePath());
                    waitProcess(process);

                    if (process.exitCode() == 0) {
                        QMessageBox::StandardButton reply;
                        reply = QMessageBox::information(this,
                                                         tr("Modemmenager"),
                                                         tr("The udev rule was created successfully. Would you like "
                                                            "to reload udev to apply the new rule?"),
                                                         QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);

                        if (reply == QMessageBox::Yes) {
                            QProcess process;
                            process.setEnvironment(QProcess::systemEnvironment());
                            process.start("pkexec", QStringList() <<
                                          "udevadm" <<
                                          "control" <<
                                          "--reload-rules");
                            waitProcess(process);

                            if (process.exitCode() == 0) {
                                showMessageDialog(tr("Command Result"),
                                                  tr("Reloaded udev rules sucessfully."),
                                                  true, false);
                            } else {
                                QString out = process.readAll();

                                if (out.isEmpty()) {
                                    showMessageDialog(tr("Command Result"),
                                                      tr("Could not reload udev rules. A reboot is probably "
                                                         "required for this change to take effect."),
                                                      false, false);
                                }
                            }
                            process.close();
                        }
                    } else {
                        showMessageDialog(tr("Command Result"),
                                          tr("Could not move rules file:\n\n"
                                             "%1").
                                          arg(QString(process.readAllStandardOutput())),
                                          false, false);
                    }
                    process.close();
                }
            }
        }
    #endif*/
}


/*

bool MainWindowNew::waitProcess(QProcess &process, bool block, int timeoutMs)
{
    bool wasEnables = isEnabled();
    bool killed     = false;

    if (block) {
        setEnabled(false);
    }

    process.waitForStarted();

    QEventLoop loop;
    QTimer     timeoutTimer;
    timeoutTimer.setSingleShot(true);
    timeoutTimer.start(timeoutMs);
    connect(&process, SIGNAL(finished(int)), &loop, SLOT(quit()));
    connect(&timeoutTimer, SIGNAL(timeout()), &loop, SLOT(quit()));
    loop.exec();

    if (process.state() == QProcess::Running) {
        process.kill();
        process.waitForFinished();
        killed = true;
    }

    setEnabled(wasEnables);

    return !killed;
}

QString MainWindowNew::runCmd(QString cmd, QStringList args)
{
    QProcess process;
    process.setEnvironment(QProcess::systemEnvironment());
    process.start(cmd, args);
    waitProcess(process);
    QString res = process.readAllStandardOutput();
    process.close();
    return res;
}

void MainWindowNew::on_pageList_currentRowChanged(int currentRow)
{
    if (currentRow >= 0) {
        ui->pageWidget->setCurrentIndex(currentRow);
    }
}

void MainWindowNew::on_actionParameterEditorBMScconf_triggered()
{
    ParameterEditor *p = new ParameterEditor(this);
    p->setAttribute(Qt::WA_DeleteOnClose);
    p->setParams(mDieBieMS->bmsConfig());
    p->show();
}

void MainWindowNew::on_actionParameterEditorInfo_triggered()
{
    ParameterEditor *p = new ParameterEditor(this);
    p->setAttribute(Qt::WA_DeleteOnClose);
    p->setParams(mDieBieMS->infoConfig());
    p->show();
}

void MainWindowNew::on_actionSaveBMSConfigurationHeader_triggered()
{
    saveParamFileDialog("mcconf", false);
}

void MainWindowNew::on_actionSaveBMSConfigurationHeaderWrap_triggered()
{
    saveParamFileDialog("mcconf", true);
}

void MainWindowNew::on_actionTerminalPrintFaults_triggered()
{
    mDieBieMS->commands()->sendTerminalCmd("faults");
    showPage("DieBieMS Terminal");
}

void MainWindowNew::on_actionTerminalShowHelp_triggered()
{
    mDieBieMS->commands()->sendTerminalCmd("help");
    showPage("DieBieMS Terminal");
}

void MainWindowNew::on_actionTerminalClear_triggered()
{
    mPageTerminal->clearTerminal();
    showPage("DieBieMS Terminal");
}

void MainWindowNew::on_actionTerminalPrintThreads_triggered()
{
    mDieBieMS->commands()->sendTerminalCmd("threads");
    showPage("DieBieMS Terminal");
}

void MainWindowNew::on_actionCanFwd_toggled(bool arg1)
{
    mDieBieMS->commands()->setSendCan(arg1);
}

void MainWindowNew::on_actionSafetyInformation_triggered()
{
    HelpDialog::showHelp(this, mDieBieMS->infoConfig(), "wizard_startup_usage");
}

void MainWindowNew::on_actionWarrantyStatement_triggered()
{
    HelpDialog::showHelp(this, mDieBieMS->infoConfig(), "wizard_startup_warranty");
}

void MainWindowNew::on_actionDieBieMSToolChangelog_triggered()
{
    HelpDialog::showHelp(this, "ENNOID-BMS Tool Changelog", Utility::vescToolChangeLog());
}

void MainWindowNew::on_actionFirmwareChangelog_triggered()
{
    HelpDialog::showHelp(this, "Firmware Changelog", Utility::fwChangeLog());
}

void MainWindowNew::on_actionLicense_triggered()
{
    HelpDialog::showHelp(this, mDieBieMS->infoConfig(), "gpl_text");
}

void MainWindowNew::on_actionStoreBMScconf_triggered()
{
    mDieBieMS->commands()->storeBMSConfig();
}
*/






