/***************************************************************************
 *	Copyright (C) 2004 by karye												*
 *	karye@users.sourceforge.net												*
 *																			*
 *	This program is free software; you can redistribute it and/or modify	*
 *	it under the terms of the GNU General Public License as published by	*
 *	the Free Software Foundation; either version 2 of the License, or		*
 *	(at your option) any later version.										*
 *																			*
 *	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.							*
 *																			*
 *	You should have received a copy of the GNU General Public License		*
 *	along with this program; if not, write to the							*
 *	Free Software Foundation, Inc.,											*
 *	59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.				*
 ***************************************************************************/

#pragma once

#include <ThreadWeaver/Job>
#include <QFileInfo>
#include <QTextStream>

#include "common.h"
#include "portagefiles.h"

/**
* @class: LoadPackageMaskJob
* @short: Thread for loading masked packages into db.
*/
class LoadPackageHardMaskJob : public ThreadWeaver::Job
{
public:
	LoadPackageHardMaskJob() = default;

	void impl( DbConnection* conn ) {

		// Collect all mask dependatoms
		QStringList linesDependAtom;
		for ( auto &itPath : KurooConfig::repoLocations() ) {
			linesDependAtom += recursiveRead( itPath + QStringLiteral("/profiles/package.mask") );
		}

		// Something is wrong, no files found, get outta here
		if ( linesDependAtom.isEmpty() )
			return;

		//setStatus( "PackageHardMask", i18n("Collecting hardmasked packages...") );

		KurooDBSingleton::Instance()->singleQuery(	QStringLiteral("CREATE TEMP TABLE packageHardMask_temp ( "
													"idPackage INTEGER, "
													"dependAtom VARCHAR(255), "
													"comment BLOB );")
													, conn);

		KurooDBSingleton::Instance()->singleQuery( QStringLiteral("BEGIN TRANSACTION;"), conn );

		QStringList commentLines;
		for ( QStringList::Iterator it = linesDependAtom.begin(), end = linesDependAtom.end(); it != end; ++it ) {

			// Collect comment lines above the dependatom
			if ( (*it).isEmpty() )
				commentLines.clear();
			else {
				if ( (*it).startsWith( u'#' ) ) {
					commentLines += (*it).section( u'#', 1, 1 ).replace(u'\'', QStringLiteral("''")).replace(u'%', QStringLiteral("&#37;"));
				}
				else {
					PortageAtom atom( *it );
					if( atom.isValid() ) {
						QString id = KurooDBSingleton::Instance()->singleQuery(
							QStringLiteral("SELECT id FROM package WHERE name = '") + atom.package() + QStringLiteral("' AND category = '") + atom.category() + QStringLiteral("' LIMIT 1;"), conn );

						if ( id.isEmpty() )
							qWarning() << QStringLiteral("Parsing package.mask. Can not find id in database for package %1/%2.")
							.arg( atom.category(), atom.package() );
						else
							KurooDBSingleton::Instance()->insert( QStringLiteral(
								"INSERT INTO packageHardMask_temp (idPackage, dependAtom, comment) "
								"VALUES ('%1', '%2', '%3');" ).arg( id, *it, commentLines.join( QStringLiteral("<br/>") ) ), conn );

					} else {
						qWarning() << QStringLiteral("Parsing package.mask(s). Can not match package %1.").arg( *it );
					}
				}
			}
		}
		KurooDBSingleton::Instance()->singleQuery( QStringLiteral("COMMIT TRANSACTION;"), conn );

		// Move content from temporary table to installedPackages
		KurooDBSingleton::Instance()->singleQuery( QStringLiteral("DELETE FROM packageHardMask;"), conn );
		KurooDBSingleton::Instance()->insert( QStringLiteral("INSERT INTO packageHardMask SELECT * FROM packageHardMask_temp;"), conn );
		KurooDBSingleton::Instance()->singleQuery( QStringLiteral("DROP TABLE packageHardMask_temp;"), conn );
		//setStatus( "PackageHardMask", i18n("Done.") );
	}
	
	void run( ThreadWeaver::JobPointer, ThreadWeaver::Thread* ) override {
		DbConnection* conn = KurooDBSingleton::Instance()->getStaticDbConnection();
		impl( conn );
		KurooDBSingleton::Instance()->returnStaticDbConnection( conn );
		PortageFilesSingleton::Instance()->refresh( PACKAGE_HARDMASK_SCANNED );
	}
	Q_DISABLE_COPY(LoadPackageHardMaskJob)
};
