// SPDX-License-Identifier: GPL-2.0-or-later
// SPDX-FileCopyrightText: 2008 Konrad Twardowski

#pragma once

#include "../kshutdown.h"

#include <QComboBox>

#ifdef Q_OS_WIN32
	#ifndef WIN32_LEAN_AND_MEAN
		#define WIN32_LEAN_AND_MEAN
	#endif // WIN32_LEAN_AND_MEAN
	#include <windows.h>
#endif // Q_OS_WIN32

class Process final: private QObject {
public:
	explicit Process(QObject *parent, const QString &command, const qint64 pid);
	QIcon icon() const;
	bool important() const;
	bool isRunning() const;

	#ifdef Q_OS_WIN32
	bool visible() const { return m_visible; }
	void setVisible(const bool value) { m_visible = value; }
	HWND windowHandle() const { return m_windowHandle; }
	void setWindowHandle(const HWND windowHandle) { m_windowHandle = windowHandle; }
	#else
	bool own() const { return m_own; }
	#endif // Q_OS_WIN32

	QString toString() const { return m_stringCache; }
private:
	Q_DISABLE_COPY(Process)
	friend class ProcessMonitor;
	qint64 m_pid;
	QString m_command; // a process command or window title (e.g. "firefox")
	QString m_stringCache = "<THEDAILYWTF>";

	#ifndef Q_OS_WIN32
	bool m_own = false;
	QString m_user = QString(); // an owner of the process (e.g. "root")
	#else
	bool m_visible = false;
	HWND m_windowHandle = NULL;
	#endif // !Q_OS_WIN32

	void makeStringCache();
};

class ProcessMonitor final: public Trigger {
	friend class Process;
public:
	explicit ProcessMonitor();
	void addProcess(Process *process);
	virtual bool canActivateAction() override;
	void initContainerWidget() override;
	virtual void readConfig() override;
	virtual void writeConfig() override;
	void setPID(const qint64 pid);
private:
	Q_DISABLE_COPY(ProcessMonitor)
	QComboBox *m_processesComboBox = nullptr;
	qint64 m_recentPid = -1;
	QList<Process*> m_processList;
	QString m_errorMessage = "";
	QString m_recentProgram = "";

	inline static QString m_noIconsLastThemeName = "";
	inline static QStringList m_noIconsList;

	void clearAll();
	void errorMessage();
	void refreshProcessList();
	void selectRecent();
	void updateStatus(const Process *process);

	// event handlers:
	void onRefresh();
};
