/***************************** LICENSE START ***********************************

 Copyright 2016 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#pragma once

#include "MvQAbstractMessageExaminer.h"
#include "MvObsSet.h"
#include "BufrFilterEngine.h"

#include <QSettings>

class QComboBox;
class QLabel;
class QPlainTextEdit;
class QSpinBox;
class QSplitter;
class QTabWidget;
class QTextEdit;
class QToolButton;
class QTreeView;
class QVBoxLayout;

class MvQArrowSpinWidget;
class MvQBufrDataModel;
class MvQTreeView;

class PlainTextWidget;

class MessageLabel;
class MvEccBufrMessage;

class BufrCompDataWidget;
class BufrFilterDef;
class BufrDataFilterDialog;
class BufrFilterDialog;
class BufrMetaData;
class MvQBufrMainPanel;
class BufrKeyWidget;
class LocationWidget;
class TreeViewSearchLine;
class MvQTreeExpandState;
class MvQBufrDumpPanel;
class BufrExpandDataModel;

class BufrJsonDumpWidget : public QWidget
{
    Q_OBJECT
public:
    BufrJsonDumpWidget(MvQBufrDumpPanel* context, QWidget* parent = nullptr);
    ~BufrJsonDumpWidget() override;

    void showError(QString errMsg);
    void saveExpandState();
    void restoreExpandState();
    void setSubsetNumber(int n);
    void updateKeyInfo();
    bool loadData(const QByteArray& json, bool compressed, QString& err);
    void clearData();

    void readSettings(QSettings& settings);
    void writeSettings(QSettings& settings);

protected slots:
    void slotDataDumpSearch();
    void dataDumpSelected(const QModelIndex& idx);
    void dataDumpDoubleClicked(const QModelIndex& idx);
    void slotCopyDumpKey();

signals:
    void subsetSelectedInKeyWidget(int subsetNumber);

private:
    void updateKeyInfo(const QModelIndex& idx);

    MvQBufrDumpPanel* context_{nullptr};
    QSplitter* splitter_{nullptr};
    QTreeView* tree_{nullptr};
    MvQBufrDataModel* model_{nullptr};
    MessageLabel* messageLabel_{nullptr};
    QToolButton* searchTb_{nullptr};
    QToolButton* keyInfoTb_{nullptr};
    TreeViewSearchLine* searchLine_{nullptr};
    BufrKeyWidget* keyWidget_{nullptr};
    MvQTreeExpandState* expand_{nullptr};
};

class BufrExpandDumpWidget : public QWidget
{
    Q_OBJECT
public:
    BufrExpandDumpWidget(QWidget* parent = nullptr);
    ~BufrExpandDumpWidget() override;

    void showError(QString errMsg);
    bool loadData(const std::string& dump, QString& err);
    void clearData();

    void readSettings(QSettings& settings);
    void writeSettings(QSettings& settings);

protected slots:
    void slotSearch();
    void slotCopyKey();

private:
    QTreeView* tree_{nullptr};
    BufrExpandDataModel* model_{nullptr};
    MessageLabel* messageLabel_{nullptr};
    QToolButton* searchTb_{nullptr};
    TreeViewSearchLine* searchLine_{nullptr};
};

class MvQBufrDumpPanel : public QWidget, public MvMessageMetaDataObserver
{
    Q_OBJECT
public:
    MvQBufrDumpPanel(QWidget* parent = nullptr);

    void init(BufrMetaData* data);
    void loadEmpty();
    void loadDumps(int msgCnt, int subsetCnt);
    void loadDumpsForSubset(int subsetCnt);
    void dataFileChanged();
    void setNavigateUncompressed(bool b);
    void loadFilterResult(MvKeyProfile* prof);
    void clear();
    void setHasFilterResult(bool);
    void selectFilterResultTab();
    int currentSubset() const { return currentSubset_; }
    int currentMessage() const { return currentMsg_; }
    BufrMetaData* data() const { return data_; }

    QList<QAction*> actionsToControl() const;

    void readSettings(QSettings& settings);
    void writeSettings(QSettings& settings);

protected slots:
    void currentDumpChanged(int);
    void setEnableDebug(bool b);

signals:
    void messageDataInvalid(int);
    void messageSelectedInMap(int);
    void locationScanProgess(int);
    void subsetSelected(int);

protected:
    void locationScanStepChanged(int) override;

private:
    enum LocationTabContent
    {
        LocationContent,
        FilterResultContent
    };
    enum DumpTabIndex
    {
        JsonTabIndex = 0,
        ExpandTabIndex = 1,
        CompTabIndex = 2,
        TableTabIndex = 3,
        DebugTabIndex = 4,
        LocationTabIndex = 5
    };

    void clearDumps();
    void clearDebugDump();
    void clearLocations();
    void loadJsonDump();
    void loadExpandDump();
    void loadTableDump();
    void loadDebugDump();
    void loadCompDump();
    void loadLocations();
    void updateKeyInfo(const QModelIndex&);
    bool doNavigateUncompressed() const;
    bool isDebugEnabled() const;
    void setLocationContent(LocationTabContent locCont);

    int currentMsg_{-1};     // starts at 0
    int currentSubset_{-1};  // starts at 1
    BufrMetaData* data_{nullptr};
    QTabWidget* dumpTab_{nullptr};

    BufrJsonDumpWidget* jsonDumpWidget_{nullptr};
    BufrExpandDumpWidget* expandDumpWidget_{nullptr};

    QTextEdit* tableTe_{nullptr};
    PlainTextWidget* debugTe_{nullptr};

    BufrCompDataWidget* compDumpWidget_{nullptr};
    MvQKeyProfileTree* compDumpTree_{nullptr};
    MvQKeyProfileModel* compDumpModel_{nullptr};
    MvQKeyProfileSortFilterModel* compDumpSortModel_{nullptr};

    MessageLabel* locationMessageLabel_{nullptr};
    LocationWidget* locationW_{nullptr};
    LocationTabContent locationContent_{LocationContent};

    QAction* actionDebug_{nullptr};
    QAction* actionNavigateUncompressed_{nullptr};

    bool messageCanBeDecoded_{true};
    bool expandDumpLoaded_{false};
    bool debugDumpLoaded_{false};
    bool navigateUncompressed_{false};
    bool compDumpLoaded_{false};
    bool locationLoaded_{false};
};

class MvQBufrMainPanel : public QWidget
{
    Q_OBJECT

public:
    MvQBufrMainPanel(bool filtered, QWidget* parent);
    void init(BufrMetaData*);
    void clear();
    MvKeyProfile* keyProfile() const;
    void loadKeyProfile(MvKeyProfile* prof);
    void reloadData(bool hasFilterResult);
    void messageFilterChanged(const BufrFilterDef&);
    void setFilterInfo(bool filtered, int oriNum, int num);
    bool doNavigateUncompressed() const;
    void loadFilterResult(MvKeyProfile*);
    void selectFilterResultTab();
    QString fileName() const;
    BufrMetaData* data() const { return data_; }
    int currentMessage() const { return dumpPanel_->currentMessage(); }

    void readSettings(QSettings& settings);
    void writeSettings(QSettings& settings);

protected slots:
    void messageSelected(int);
    void messageChangedInGoto(int value);
    void subsetChangedInGoto(int value);
    void subsetChangedInDump(int currentSubset);
    void messageSelectedInMap(int);
    void navigateUncompressedChanged(bool);
    void keyProfileReady();
    void keyProfileLoadFinished();

signals:
    void newMessageSelected(int);
    void keyProfileChanged();
    void messageNumDetermined();

private:
    BufrMetaData* data_{nullptr};
    MvQMessagePanel* messagePanel_{nullptr};
    MvQBufrDumpPanel* dumpPanel_{nullptr};
    MessageControlPanel* gotoPanel_{nullptr};
    QSplitter* dataSplitter_{nullptr};
    bool navigateUncompressed_;
    bool inProfileLoad_;
    QAction* actionDebug_{nullptr};
    QAction* actionNavigateUncompressed_{nullptr};
};

class BufrExaminer : public MvQAbstractMessageExaminer, public BufrFilterEngineObserver
{
    Q_OBJECT

public:
    BufrExaminer(QWidget* parent = nullptr);
    ~BufrExaminer() override;

    void notifyBufrFilterProgress(int n) override;

protected slots:
    void slotShowAboutBox() override;
    void slotStatusMessage(QString);
    void slotLoadFile(QString) override;
    void slotUncompressedMode(bool);
    void slotFilterEdit();
    void slotFilterRevert();
    void slotRunFilter(const BufrFilterDef&);
    void slotSaveFilteredFile(bool);
    void newMessageLoaded(int msg);
    void updateFileInfoLabel() override;
    void initFilterEditorHelpers();

signals:
    void filterProgess(int);

protected:
    MvKeyProfile* loadedKeyProfile() const override;

private:
    enum MainTabIndex
    {
        OriiginalTabIndex = 0,
        FilteredTabIndex = 1
    };

    void setupFileMenu() override;
    void setupFilterMenu();

    void initMain(MvMessageMetaData* data) override;
    void initDumps() override;
    void initAllKeys() override;
    void addCloseButtonFilteredTab();
    void createFilteredPanel();
    void loadKeyProfile(MvKeyProfile*) override;
    void loadFile(QString);
    void loadEmptyFile(QString f);
    void loadFilteredFile(QString, MvKeyProfile*);
    void loadFilteredEmptyFile(QString f);

    void writeSettings();
    void readSettings();

    QTabWidget* mainTab_{nullptr};
    MvQBufrMainPanel* mainPanel_{nullptr};
    MvQBufrMainPanel* filteredPanel_{nullptr};
    BufrMetaData* filteredData_{nullptr};
    bool messageCanBeDecoded_{false};
    QAction* actionFilterEdit_{nullptr};
    QAction* actionFilterRemove_{nullptr};
    QAction* actionSave_{nullptr};
    BufrFilterDialog* filterDialog_{nullptr};
};
