#pragma once

#include <entities/script.h>

#include <QDateTime>

#include "masterdialog.h"

namespace Ui {
class ScriptRepositoryDialog;
}

class QSplitter;
class QTreeWidgetItem;

class ScriptRepositoryDialog : public MasterDialog {
    Q_OBJECT

   public:
    explicit ScriptRepositoryDialog(QWidget *parent = nullptr, bool checkForUpdates = false);
    ~ScriptRepositoryDialog();

    Script getLastInstalledScript();

    void searchForUpdates();
    void searchForUpdatesForScripts(const QList<Script> &scripts);
    int updateAllScripts(bool showMessage = true);
    static void checkForScriptUpdates(QWidget *parent = nullptr);
    static int updateAllScriptUpdates(QWidget *parent = nullptr);

   signals:
    void updateFound();
    void noUpdateFound();

   private slots:
    void on_scriptTreeWidget_currentItemChanged(QTreeWidgetItem *current,
                                                QTreeWidgetItem *previous);

    void on_installButton_clicked();

    void on_searchScriptEdit_textChanged(const QString &arg1);

    void on_updateAllButton_clicked();

    void on_automaticScriptUpdatesCheckBox_toggled(bool checked);

   private:
    Ui::ScriptRepositoryDialog *ui;
    QString _codeSearchUrl;
    QString _rawContentUrlPrefix;
    QSplitter *_mainSplitter;
    bool _checkForUpdates;
    QString _searchString;
    Script _lastInstalledScript;
    QHash<QString, ScriptInfoJson> _scriptMetaDataCache;
    QHash<QString, QString> _scriptMetaDataJsonTextCache;
    QHash<QString, QString> _scriptChangelogCache;
    QDateTime _lastScriptMetaDataCacheUpdateTime;

    void searchScript();

    void setupMainSplitter();

    void storeSettings();

    void enableOverview(bool enable);

    ScriptInfoJson getCurrentScriptInfoJson();

    QString getCurrentInfoJsonString();

    void reloadCurrentScriptInfo();
    QString loadScriptChangelog(const ScriptInfoJson &infoJson);
    void updateScriptChangelog(const ScriptInfoJson &infoJson, const Script &script);

    bool isScriptCacheExpired();
    bool loadScriptRepositoryMetaData();
    void parseScriptRepositoryMetaData(const QByteArray &arr);
    void addScriptTreeWidgetItem(const ScriptInfoJson &scriptInfoJson);
    bool hasScriptUpdate(const Script &script) const;
    QList<Script> scriptsWithUpdates(const QList<Script> &scripts) const;
    bool installScript(const ScriptInfoJson &infoJson, bool showMessages, bool refreshAfterInstall);
};
