#include "edockwidget.h"
#include "cdpultwindow.h"
#include "cdutils_core.h"
#include "cdutils_k.h"
#include "cdutils_x.h"
#include "cdutils_m.h"
#include "qcd_core.h"
#include "qcd_view.h"
#include "qcd_model.h"
#include "qcd_modedialog.h"
#include "chunkstream.h"
#include "qvariantedit.h"
#include "piqt.h"
#include "piqt_highlighter.h"
#include "qcodeedit.h"
#include <QFileDialog>
#include <QScrollBar>
#include <QImageReader>
#include <QMessageBox>

using namespace CDUtils;


CDPultWindow::CDPultWindow(QWidget *parent) : EMainWindow(parent), Ui::CDPultWindow() {
	setupUi(this);
	centralWidget()->hide();
	setTabPosition(Qt::AllDockWidgetAreas, QTabWidget::North);
	CDCore::instance()->initPult();
	def_config = codeConfig->text();
	checkDefaultConfig->setChecked(true);
	new ConfigHighlighter(codeConfig->document());
	widgetK->setType(CDUtils::CDType::cdK);
	widgetX->setType(CDUtils::CDType::cdX);
	widgetC->setType(CDUtils::CDType::cdC);
	widgetM->setType(CDUtils::CDType::cdM);
	editFileK->setValue(QVariant::fromValue(QAD::File("", "*.dat")));
	editFileX->setValue(QVariant::fromValue(QAD::File("", "*.dat")));
	editFileC->setValue(QVariant::fromValue(QAD::File("", "*.dat")));
	editFileM->setValue(QVariant::fromValue(QAD::File("", "*.dat")));
	log_icons[CDViewWidget::OKIcon]   = QIcon(":/icons/dialog-ok-apply.png");
	log_icons[CDViewWidget::FailIcon] = QIcon(":/icons/dialog-cancel.png");
	log_icons[CDViewWidget::WaitIcon] = QIcon(":/icons/timer.png");
	setRecentMenu(menuOpen_recent);
	ribbon = new Ribbon(this);
	session.setFile("session_cdpult.conf");
	session.addEntry(this);
	session.addEntry(ribbon->tabWidget());
	session.load();
	reset();
	connect(widgetK, SIGNAL(addToLog(CDViewWidget::LogIcon,QString)), this, SLOT(addToLog(CDViewWidget::LogIcon,QString)));
	connect(widgetX, SIGNAL(addToLog(CDViewWidget::LogIcon,QString)), this, SLOT(addToLog(CDViewWidget::LogIcon,QString)));
	connect(widgetC, SIGNAL(addToLog(CDViewWidget::LogIcon,QString)), this, SLOT(addToLog(CDViewWidget::LogIcon,QString)));
	connect(widgetM, SIGNAL(addToLog(CDViewWidget::LogIcon,QString)), this, SLOT(addToLog(CDViewWidget::LogIcon,QString)));
	connect(widgetK->view, SIGNAL(changedGlobal()), widgetDirectK, SLOT(changedGlobal()));
	connect(widgetX->view, SIGNAL(changedGlobal()), widgetGraphics, SLOT(changedGlobal()));
	connect(widgetX->view, SIGNAL(receivedX()), widgetGraphics, SLOT(receivedX()));
	connect(widgetM->view, SIGNAL(messageReceived(QString,int,QString)), this, SLOT(messageReceived(QString,int,QString)));
	QCDCore::instance()->bindWidget(widgetK->view);
	QCDCore::instance()->setDirectKEnabled(true);
	X.start();
	if (windowState() == Qt::WindowMinimized)
		setWindowState(Qt::WindowNoState);
}


CDPultWindow::~CDPultWindow() {
}


void CDPultWindow::loadFile(const QString & fp) {
	load(fp);
}


void CDPultWindow::apply(bool sessions) {
	CDCore::instance()->stop();
	widgetK->setFile(editFileK->value().value<QAD::File>().file);
	widgetX->setFile(editFileX->value().value<QAD::File>().file);
	widgetC->setFile(editFileC->value().value<QAD::File>().file);
	widgetM->setFile(editFileM->value().value<QAD::File>().file);
	if (checkDefaultConfig->isChecked())
		CDCore::instance()->initPult();
	else
		CDCore::instance()->init(Q2PIString(codeConfig->text()), true);
	widgetX->view->startX();
	if (sessions) {
		widgetGraphics->load(session_gr);
		widgetDirectK->load(session_dk);
		if (!session_mw.isEmpty())
			restoreState(session_mw);
		X.lock();
		PIVector<PIDeque<int> > x_list = X.enabledList();
		X.unlock();
		piForeachC (PIDeque<int> & p, x_list)
			X.enable(X[p]);
		((CDItemModel*)widgetX->view->model())->updateModel();
		widgetX->view->expandAll();
	}
	dockCDKView->setVisible(checkHasK->isChecked());
	dockCDXView->setVisible(checkHasX->isChecked());
	dockCDCView->setVisible(checkHasC->isChecked());
	dockCDMView->setVisible(checkHasM->isChecked());
	QMetaObject::invokeMethod(this, "changedDock", Qt::QueuedConnection);
}


void CDPultWindow::closeEvent(QCloseEvent *e) {
	EMainWindow::closeEvent(e);
	if (!e->isAccepted())
		return;
	QApplication::closeAllWindows();
	session.save();
	session.setFile(QString());
}


void CDPultWindow::reset(bool full) {
	setWindowTitle(QString("CD Pult"));
	widgetK->reset();
	setChanged(false);
}


bool CDPultWindow::load(const QString & path) {
	qApp->setOverrideCursor(Qt::WaitCursor);
	QPIConfig conf(path, QIODevice::ReadOnly);
	QAD::File f = editFileK->value().value<QAD::File>();
	checkSyncFiles->setChecked(false);
	editFileK->setValue(QVariant::fromValue(QAD::File(conf.getValue("file_k").value(), f.filter)));
	editFileX->setValue(QVariant::fromValue(QAD::File(conf.getValue("file_x").value(), f.filter)));
	editFileC->setValue(QVariant::fromValue(QAD::File(conf.getValue("file_c").value(), f.filter)));
	editFileM->setValue(QVariant::fromValue(QAD::File(conf.getValue("file_m").value(), f.filter)));
	checkSyncFiles->setChecked(conf.getValue("sync_files"));
	lineSessionName->setText(conf.getValue("session_name"));
	last_icon = conf.getValue("icon_path", "").value();
	setAppIcon(conf.getValue("icon", QByteArray()));
	checkHasK->setChecked(conf.getValue("has_k"));
	checkHasX->setChecked(conf.getValue("has_x"));
	checkHasC->setChecked(conf.getValue("has_c"));
	checkHasM->setChecked(conf.getValue("has_m"));
	checkDefaultConfig->setChecked(conf.getValue("default_config"));
	codeConfig->setText(QByteArray2QString(conf.getValue("config", QByteArray())));
	if (codeConfig->text().isEmpty())
		codeConfig->setText(def_config);
	session_gr = conf.getValue("session_gr", QByteArray());
	session_dk = conf.getValue("session_dk", QByteArray());
	session_mw = conf.getValue("session_mw", QByteArray());
	setChanged(false);
	file_name = path;
	apply(true);
	qApp->restoreOverrideCursor();
	return true;
}


bool CDPultWindow::save(const QString & path) {
	session_gr = widgetGraphics->save();
	session_dk = widgetDirectK->save();
	session_mw = saveState();
	QPIConfig conf(path, QIODevice::ReadWrite);
	conf.clear();
	conf.setValue("file_k", editFileK->value().value<QAD::File>().file);
	conf.setValue("file_x", editFileX->value().value<QAD::File>().file);
	conf.setValue("file_c", editFileC->value().value<QAD::File>().file);
	conf.setValue("file_m", editFileM->value().value<QAD::File>().file);
	conf.setValue("sync_files", checkSyncFiles->isChecked());
	conf.setValue("session_name", lineSessionName->text());
	conf.setValue("icon_path", last_icon);
	conf.setValue("icon", appIcon());
	conf.setValue("has_k", checkHasK->isChecked());
	conf.setValue("has_x", checkHasX->isChecked());
	conf.setValue("has_c", checkHasC->isChecked());
	conf.setValue("has_m", checkHasM->isChecked());
	conf.setValue("default_config", checkDefaultConfig->isChecked());
	conf.setValue("config", QString2QByteArray(codeConfig->text()));
	conf.setValue("session_gr", session_gr);
	conf.setValue("session_dk", session_dk);
	conf.setValue("session_mw", session_mw);
	file_name = path;
	return true;

	//widgetK->setFile(path);
	//widgetK->save();
}


void CDPultWindow::loadingSession(QPIConfig & conf) {
	setRecentFiles(conf.getValue("recent files", QStringList()));
}


void CDPultWindow::savingSession(QPIConfig & conf) {
	conf.setValue("recent files", recentFiles());
}


QByteArray CDPultWindow::appIcon() const {
	QByteArray ret;
	if (icon.isNull()) return ret;
	QBuffer buff(&ret);
	buff.open(QIODevice::WriteOnly);
	icon.save(&buff, "png");
	//qDebug() << "s" << ret.size();
	return ret;
}


void CDPultWindow::setAppIcon(QByteArray ba) {
	if (ba.isEmpty()) {
		icon = QImage();
		setWindowIcon(QIcon());
		return;
	}
	//qDebug() << "l" << ba.size();
	icon = QImage::fromData(ba);
	setWindowIcon(QIcon(QPixmap::fromImage(icon)));
	//qDebug() << QApplication::windowIcon().availableSizes();
}


void CDPultWindow::addToLog(CDViewWidget::LogIcon icon, const QString & msg) {
	QListWidgetItem * ni = new QListWidgetItem(log_icons[icon], "(" + QTime::currentTime().toString() + ") " + msg);
	bool s = listLog->verticalScrollBar()->value() == listLog->verticalScrollBar()->maximum();
	listLog->addItem(ni);
	if (s) listLog->scrollToBottom();
}


void CDPultWindow::messageReceived(QString path, int type, QString msg) {
	MessageType mt = (MessageType)type;
	const CDType & t(M.root()[CDCore::stringToPath(Q2PIString(path))]);
	if (t.cd_type() != CDType::cdM) return;
	if (mt == MessageBox)
		QMessageBox::information(this, windowTitle(), QString("[%1]\n%2").arg(PI2QString(t.name()), msg));
}


void CDPultWindow::on_editFileK_valueChanged(const QVariant & p) {
	if (!checkSyncFiles->isChecked()) return;
	QFileInfo fi(p.value<QAD::File>().file);
	if (fi.path().isEmpty()) return;
	QString n = fi.baseName();
	QString xn(n), cn(n), mn(n);
	if (n.contains("k")) {
		xn.replace(n.indexOf("k"), 1, "x");
		cn.replace(n.indexOf("k"), 1, "c");
		mn.replace(n.indexOf("k"), 1, "m");
	} else {
		xn += "_x";
		cn += "_c";
		mn += "_m";
	}
	QString ext = fi.suffix(), dot, dir;
	QString kfn(fi.filePath());
	if (!ext.isEmpty()) {
		kfn.chop(ext.size());
		if (kfn.endsWith(".")) {
			kfn.chop(1);
			dot = ".";
		}
	}
	if (!fi.path().isEmpty() && fi.path() != ".") {
		dir = fi.path();
		if (!dir.endsWith("/"))
			dir += "/";
	}
	QAD::File f = editFileK->value().value<QAD::File>();
	f.file = dir + xn + dot + ext; editFileX->setValue(QVariant::fromValue(f));
	f.file = dir + cn + dot + ext; editFileC->setValue(QVariant::fromValue(f));
	f.file = dir + mn + dot + ext; editFileM->setValue(QVariant::fromValue(f));
}


void CDPultWindow::on_buttonSessionApply_clicked() {
	apply(false);
}


void CDPultWindow::on_lineSessionName_textChanged(const QString & t) {
	setWindowTitle(QString("CD Pult - %1").arg(t));
}


void CDPultWindow::on_buttonIcon_clicked() {
	QList<QByteArray> ifl = QImageReader::supportedImageFormats();
	QStringList sfl; foreach (QByteArray s, ifl) sfl << ("*." + QString(s).toLower());
	QString f = QFileDialog::getOpenFileName(this, tr("Select icon"), last_icon, tr("Images") + " (" + sfl.join(" ") + ")");
	if (f.isEmpty()) return;
	last_icon = f;
	icon = QImage(last_icon);
	setWindowIcon(QIcon(QPixmap::fromImage(icon)));
}
