#ifndef DEVICE_WIDGET_H
#define DEVICE_WIDGET_H

#include <QDialog>
#include <QIcon>
#include <pistring.h>
#include "SH_client_channel.h"
#include "SH_network_types.h"

class QTreeWidgetItem;
class PISerial;
class __SerialProxy;

namespace Ui {
	class DeviceWidget;
	class DeviceWidgetDialog;
}

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

	void setReadTimeout(int to);
	int readTimeout() const;
	void hideServer();

	void write(const PIByteArray & data);
	void write(const void * data, int size) {write(PIByteArray(data, size));}
	PIByteArray read(int max_size = -1, int timeout = -1);
	bool isOpened() const;
	bool isStarted() const {return started_;}
	bool isLocalDevice() const;

	void open();
	void open(const QString & com);
	void close();
	void startRead();
	void stopRead();

	PISerial * serial() {return ser;}

private:
	void timerEvent(QTimerEvent * e) override;
	void showDevices();
	void selectServerDevice(int index);
	void setState(QString t);
	void serverDisconnect();
	EVENT_HANDLER(void, disconnected);
	EVENT_HANDLER(void, connected);
	EVENT_HANDLER1(void, receiveEvent, PIByteArray, data);

	Ui::DeviceWidget * ui;
	Ui::DeviceWidgetDialog * ui_d;
	QDialog dialog;
	QIcon icon_on, icon_off, icon_open, icon_close;
	int timer_ao, timer_update, timeout_r, timer_pip;
	bool started_;

	PISerial * ser;
	PIString server_device;
	__SerialProxy * proxy;
	PIStringList last_devlist;
	PIVector<ServerDevice> server_devices;
	PIByteArray server_packet;
	PIMutex srec_mutex;

	SHClientChannel channel;
	
public slots:

private slots:
	void on_checkAutoOpen_toggled(bool on);
	void on_buttonDevicesRefresh_clicked() {showDevices();}
	void on_buttonDisconnect_clicked();
	void on_tabWidget_currentChanged(int index);
	void on_treeServers_serverSelected(PacketServerInfo info);
	void on_treeDevices_itemDoubleClicked(QTreeWidgetItem * item, int column);
	void on_spinReadTimeout_valueChanged(int v);
	void on_buttonDeviceDialogOpen_clicked();

	void on_buttonDeviceOpen_clicked();
	void on_buttonDeviceConfigure_clicked();

	void showServerDevices();
	void serverError(QString msg);
	void sessionSave(QByteArray * data);
	void sessionLoad(QByteArray * data);

signals:
	void opened();
	void closed();
	void readed(QByteArray);

	
};

#endif // DEVICE_WIDGET_H
