#include "cdviewwidget.h"
#include "cdutils_core.h"
#include "qcd_core.h"
#include "qcd_model.h"
#include "qcd_modedialog.h"
#include "qvariantedit.h"
#include <QFileDialog>


CDViewWidget::CDViewWidget(QWidget * parent) : QWidget(parent), Ui::CDViewWidget() {
	qRegisterMetaType<CDViewWidget::LogIcon>("CDViewWidget::LogIcon");
	setupUi(this);
	connect(view, SIGNAL(sendSucceed()),    this, SLOT(sended()));
	connect(view, SIGNAL(receiveSucceed()), this, SLOT(received()));
	connect(view, SIGNAL(sendFailed()),     this, SLOT(sendFailed()));
	connect(view, SIGNAL(receiveFailed()),  this, SLOT(receiveFailed()));
}


CDViewWidget::~CDViewWidget() {
}


void CDViewWidget::reset() {
	setFile("");
}


void CDViewWidget::setType(int t) {
	view->setType((CDUtils::CDType::cdT)t);
	tl_u = view->typeLetter().toUpper();
	tl_l = view->typeLetter().toLower();
	view->refresh();
}


void CDViewWidget::setFile(const QString & f) {
	view->setFile(f);
	view->load();
}


void CDViewWidget::on_buttonSend_clicked() {
	if (view->inProgress()) {addToLog(WaitIcon, "processing..."); return;}
	addToLog(WaitIcon, "Sending " + tl_u + "...");
	view->send();
}


void CDViewWidget::on_buttonReceive_clicked() {
	if (view->inProgress()) {addToLog(WaitIcon, "processing..."); return;}
	addToLog(WaitIcon, "Receiving " + tl_u + "...");
	view->receive();
}


void CDViewWidget::on_buttonLoad_clicked() {
	view->load();
}


void CDViewWidget::on_buttonSave_clicked() {
	view->save();
}


void CDViewWidget::on_buttonParse_clicked() {
	QString path = QFileDialog::getOpenFileName(this, "Select header file", "",
												QString("%1 Description(%2_description.h);;Headers(*.h)").arg(tl_u, tl_l));
	if (path.isEmpty()) return;
	CDUtils::UpdateModeFlags mode = CDUtils::SaveByName;
	if (!view->root()->isEmpty()) {
		QCDModeDialog cdm;
		if (cdm.exec() != QDialog::Accepted) return;
		mode = cdm.mode();
	}
	view->buildFromHeader(path, mode);
}
