#include "clients_list.h"
#include "SH_network_types.h"
#include "SH_platform.h"
#include "SH_runtime.h"
#include "ui_clients_list.h"
#include <QMetaObject>
#include <piqt.h>


enum ColumnnClient {
	ccOS,
	ccArch,
	ccHostname,
	ccID,
	ccRole,
	ccUserRole,
	ccChannel,
	ccIP,
	ccConnected,
	ccSendBytes,
	ccRecBytes,
	ccSendSpeed,
	ccRecSpeed,
};


ClientsList::ClientsList(QWidget * parent): QTreeWidget(parent){
	Q_INIT_RESOURCE(ui_tools);
	ui = new Ui::ClientsList();
	ui->setupUi(this);
	ose = SHPlatform::staticMetaObject.enumerator(SHPlatform::staticMetaObject.indexOfEnumerator("OSType"));
	rolee = SHServer::staticMetaObject.enumerator(SHServer::staticMetaObject.indexOfEnumerator("ClientRole"));
	cte = SHNetworkTypes::staticMetaObject.enumerator(SHNetworkTypes::staticMetaObject.indexOfEnumerator("ChannelType"));
	for (int i = 0; i < ose.keyCount(); ++i)
		os_icons[ose.value(i)] = QIcon(QString(":/icons/OS-%1.png").arg(QString(ose.key(i))));
}


ClientsList::~ClientsList() {
}


void ClientsList::set(const PIVector<ServerClientInfo> & clients) {
	for (int i = topLevelItemCount() - 1; i >= clients.size_s(); --i)
		delete takeTopLevelItem(i);
	for (int i = topLevelItemCount(); i < clients.size_s(); ++i)
		addTopLevelItem(new QTreeWidgetItem());
	for (int i = 0; i < topLevelItemCount(); ++i) {
		QTreeWidgetItem * ti = topLevelItem(i);
		const ServerClientInfo & info(clients[i]);
		ti->setText(ccIP, info.address);
		ti->setIcon(ccOS, os_icons.value(int(info.OS_type)));
		ti->setText(ccOS, QString("%1 (%2)").arg(QString(ose.valueToKey(int(info.OS_type)))).arg(info.OS_version));
		ti->setText(ccArch, info.OS_arch);
		ti->setText(ccHostname, info.hostname);
		ti->setText(ccID, QString::number(info.id, 16).rightJustified(8, '0'));
		ti->setText(ccRole, QString(rolee.valueToKey(int(info.role))).mid(4));
		ti->setText(ccUserRole, QString("%1 (%2)").arg(info.user_role).arg(RUNTIME->server_project.roleByIndex(info.user_role).displayName()));
		ti->setText(ccChannel, cte.valueToKey(info.channel));
		ti->setText(ccConnected, info.connected_time.toString());
		ti->setText(ccSendBytes, PI2QString(PIString::readableSize(info.sended_bytes)));
		ti->setText(ccRecBytes , PI2QString(PIString::readableSize(info.received_bytes)));
		ti->setText(ccSendSpeed, info.send_speed);
		ti->setText(ccRecSpeed , info.receive_speed);
	}
	update();
}
