#ifndef SH_SERVERS_TREE_WIDGET_H
#define SH_SERVERS_TREE_WIDGET_H

#include <QWidget>
#include <QModelIndex>
#include <QIcon>
#include <QMenu>
#include <QGesture>
#include <piobject.h>
#include <pimutex.h>
#include "SH_network_types.h"

namespace Ui {
	class SHServersTreeWidget;
}

class SHClientChannel;

class SHServersTreeWidget: public QWidget, public PIObject {
	Q_OBJECT
	PIOBJECT(SHServersTreeWidget)
public:
	explicit SHServersTreeWidget(QWidget * parent = 0);
	~SHServersTreeWidget();

	void setPultView();
	void selectCurrentServer();
	
	void clear();
	void addServer(const PacketServerInfo & info);
	bool isRequesting() const {return requesting;}

	void startBroadcast();
	void stopBroadcast();

	PIVector<PacketServerInfo> servers() const;
	PacketServerInfo currentServer() const;
	
private:
	bool event(QEvent * e) override;
	void timerEvent(QTimerEvent * e) override;
	QString queryAddress();
	void loadServers();
	void saveServers(const PacketServerInfo & to_remove = PacketServerInfo());
	void procGesture(QGesture * g);

	EVENT_HANDLER1(void, broadcastReceiveEvent, PIByteArray, data);
	EVENT_HANDLER(void, connected);
	EVENT_HANDLER1(void, receiveEvent, PIByteArray, data);

	Ui::SHServersTreeWidget * ui;
	PIVector<PacketServerInfo> servers_;
	PIMap<uint, SHClientChannel * > channels;
	SHClientChannel * bc_channel;
	SHClientChannel * channel = nullptr;
	QIcon icon_state[3];
	QMenu popup_menu;
	mutable PIMutex smutex;
	int timer_pip;
	bool changed = false, requesting = false, loading = true;

private slots:
	void fill();
	void setIcons();

	void on_tree_customContextMenuRequested(const QPoint & pos);
	void on_tree_doubleClicked(QModelIndex);
	void on_buttonAddServer_clicked();
	void on_buttonUpdate_clicked();
	void on_actionRemove_triggered();
	
public slots:
	void addressEntered(QString addr);
	
signals:
	void serverSelected(PacketServerInfo);
	void addressRequest(QString);

};

#endif // SH_SERVERS_TREE_WIDGET_H
