#include <QDir>
#include "cdutils_k.h"
#include "qcd_kview.h"
#include "qcd_kmodel.h"
#include "piqt.h"
#include "pifile.h"

using namespace CDUtils;


CDKView::CDKView(QWidget *parent) : QTreeView(parent) {
	kmodel = 0;
	CONNECTU(&K, sended, this, cdk_sendSucceed);
	CONNECTU(&K, sendFailed, this, cdk_sendFailed);
	CONNECTU(&K, received, this, cdk_receiveSucceed);
	CONNECTU(&K, receiveFailed, this, cdk_receiveFailed);
	connect(this, SIGNAL(_qcdk_sendFailed()), this, SLOT(k_sendFailed()), Qt::QueuedConnection);
	connect(this, SIGNAL(_qcdk_sendSucceed()), this, SLOT(k_sendSucceed()), Qt::QueuedConnection);
	connect(this, SIGNAL(_qcdk_receiveFailed()), this, SLOT(k_receiveFailed()), Qt::QueuedConnection);
	connect(this, SIGNAL(_qcdk_receiveSucceed()), this, SLOT(k_receiveSucceed()), Qt::QueuedConnection);
}


CDKView::~CDKView() {
	if (kmodel) delete kmodel;
	kmodel = 0;
}


void CDKView::refresh() {
	if (!kmodel) {
		//K.reinitConnection(K.pultConfig());
		kmodel = new CDKItemModel();
		setModel(kmodel);
		setItemDelegateForColumn(4, new CDKDelegate());
	}
	kmodel->rebuildModel();
	expandAll();
	for (int i=0; i<6; i++) resizeColumnToContents(i);
}


void CDKView::setKFile(const QString &filename) {
	K.setFileName(Q2PIString(filename));
}


void CDKView::startPing() {
	K.startPing();
}


void CDKView::sendK() {
	busyStatusChanged(true);
	K.send();
}


void CDKView::receiveK() {
	busyStatusChanged(true);
	K.request();
}


void CDKView::saveK() {
	K.writeFile();
}


void CDKView::loadK() {
	K.readFile();
	K.calculate();
	refresh();
}


void CDKView::clearK() {
	K.root() = CDSection();
	refresh();
}


void CDKView::buildFromHeader(const QString &kdescription, int mode) {
	if (kdescription.isEmpty()) return;
	PIString kdesc_file = Q2PIString(QDir::current().relativeFilePath(kdescription));
	PIFile f(kdesc_file, PIIODevice::ReadOnly);
	K.update(&f, mode);
	refresh();
}


void CDKView::calculateK() {
	K.calculate();
}


void CDKView::k_sendFailed() {
	busyStatusChanged(false);
	emit messageStatus("send failed");
	emit KSendFailed();
}


void CDKView::k_sendSucceed() {
	busyStatusChanged(false);
	emit messageStatus("send success");
	emit KSendSucceed();
}


void CDKView::k_receiveFailed() {
	busyStatusChanged(false);
	emit messageStatus("receive failed");
	emit KReceiveFailed();
}


void CDKView::k_receiveSucceed() {
	busyStatusChanged(false);
	emit messageStatus("receive success");
	refresh();
	emit KReceiveSucceed();
}

