/*
 *  Copyright (C) 2007-2008 CMM Sigma Andrzej Chmielowiec <cmmsigma@cmmsigma.eu>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 3
 *  as published by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

#include <QIcon>

#include "STokenFileItem.h"
#include "FileDialogWPR.h"
#include "QDetailsMessageBox.h"
#include "crd_ut10xx.h"
#include "MainWindow.h"

STokenFileItem::STokenFileItem(int fileId, CRD_UT10XX_t *ut, TreeItem *parent): TreeItem(parent)
{
	mUt = ut;
	mId = fileId;
	mTreeWidgetItem = new QTreeWidgetItem;
	
	if (mUt->file_types[mId] & CRD_UT10XX_FTM_PRINT)
	{
		QTextEdit *widget = new QTextEdit;
		widget->setFontFamily(QString("Courier New"));
		widget->setLineWrapMode(QTextEdit::NoWrap);
		widget->setText(QString(readFileContents()));
		widget->setReadOnly(true);
		mMainWidget = widget;
	}
	else
	{
		mMainWidget = new QWidget;
	}
	
	setPage(mMainWidget);
}

STokenFileItem::~STokenFileItem()
{
	delete mTreeWidgetItem;
}

int
STokenFileItem::id()
{
	return mId;
}

QTreeWidgetItem*
STokenFileItem::treeWidgetItem()
{
	return mTreeWidgetItem;
}

void
STokenFileItem::refresh()
{
	QString name = trUtf8(mUt->file_names[mId]);
	QVariant fileName;
	QVariant fileSize;
	QVariant fileIcon;
	
	if ( name.endsWith(QString(".crt"), Qt::CaseInsensitive)
		|| name.endsWith(QString(".cer"), Qt::CaseInsensitive)
		|| name.endsWith(QString(".cert"), Qt::CaseInsensitive) )
	{
		fileIcon = QIcon(QString(":img/filetype_usercert.png"));
	}
	else if ( name.endsWith(QString(".req"), Qt::CaseInsensitive) )
	{
		fileIcon = QIcon(QString(":img/filetype_userreq.png"));
	}
	else if ( name.endsWith(QString(".html"), Qt::CaseInsensitive)
		|| name.endsWith(QString(".htm"), Qt::CaseInsensitive) )
	{
		fileIcon = QIcon(QString(":img/filetype_html.png"));
	}
	else if ( name.endsWith(QString(".txt"), Qt::CaseInsensitive)
		|| name.endsWith(QString(".text"), Qt::CaseInsensitive) )
	{
		fileIcon = QIcon(QString(":img/filetype_txt.png"));
	}
	else if ( name.endsWith(QString(".key"), Qt::CaseInsensitive)
		|| name.endsWith(QString(".pub"), Qt::CaseInsensitive) )
	{
		fileIcon = QIcon(QString(":img/filetype_key.png"));
	}
	else if ( name.endsWith(QString(".conf"), Qt::CaseInsensitive)
		|| name.endsWith(QString(".cnf"), Qt::CaseInsensitive) )
	{
		fileIcon = QIcon(QString(":img/filetype_conf.png"));
	}
	else if ( name.endsWith(QString(".bin"), Qt::CaseInsensitive) )
	{
		fileIcon = QIcon(QString(":img/filetype_binary.png"));
	}
	else
	{
		fileIcon = QIcon(QString(":img/filetype_unknown.png"));
	}
	
	fileName = name;
	fileSize = QString("%1").arg(mUt->file_sizes[mId]);
	
	setData(fileName, Qt::DisplayRole);
	setData(fileIcon, Qt::DecorationRole);
	
	mTreeWidgetItem->setData(0, Qt::DisplayRole, fileName);
	mTreeWidgetItem->setData(0, Qt::DecorationRole, fileIcon);
	mTreeWidgetItem->setData(1, Qt::DisplayRole, fileSize);
	mTreeWidgetItem->setTextAlignment(1, Qt::AlignRight);
}

QByteArray
STokenFileItem::readFileContents()
{
	CRD_UT10XX_file_t *fd = 0;
	const char *fName = mUt->file_names[mId];
	bool error = false;
	QByteArray buf;
	
	CRD_UT10XX_session_open(mUt);
		
	if (!error && ((fd = CRD_UT10XX_file_open(mUt, fName)) == 0))
	{
		QDetailsMessageBox::critical(MainWindow::mainWnd, tr("Error"), tr("Cannot open file %1 on token.").arg(fName), 
			CRD_UT10XX_lib_detail_error_desc(mUt));
		error = true;
	}
	
	if (!error)
		buf.resize(fd->size);
	
	if (!error && (CRD_UT10XX_file_read(fd, buf.data(), fd->size) < 0))
	{
		QDetailsMessageBox::critical(MainWindow::mainWnd, tr("Error"), tr("Cannot read file %1 on token.").arg(fName), 
			CRD_UT10XX_lib_detail_error_desc(mUt));
		error = true;
	}
	
	if (fd && (CRD_UT10XX_file_close(fd) < 0))
	{
		QDetailsMessageBox::critical(MainWindow::mainWnd, tr("Error"), tr("Cannot close file %1 on token.").arg(fName), 
			CRD_UT10XX_lib_detail_error_desc(mUt));
		error = true;
	}
	
	CRD_UT10XX_session_close(mUt);
	
	return buf;
}

void
STokenFileItem::displayContextMenu(const QModelIndex &index)
{
	QMenu *menu = new QMenu();
	menu->addAction(QIcon(QString(":img/filecmd_saveas.png")), tr("Save as"), this, SLOT(saveTokenFile()));
	menu->exec(QCursor::pos());
}

void
STokenFileItem::saveTokenFile()
{
	QByteArray content = readFileContents();
	QString dstFileName;

	const char *fName = mUt->file_names[mId];
	QString fileName = QDir::homePath() + QDir::separator() + fName;
	dstFileName = FileDialogWPR::getSaveFileName(mMainWidget, tr("Save as"), fileName);

	if (dstFileName.isEmpty())
		return;

	QFile dstFile(dstFileName);
	dstFile.open(QIODevice::WriteOnly | QIODevice::Truncate);
	dstFile.write(content);
	dstFile.close();
}
