/***************************************************************************
*   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 <QTextStream>

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

/**
* @class: LoadPackageKeywordsJob
* @short: Thread for loading packages keyword-unmasked by user.
*/
class LoadPackageKeywordsJob : public ThreadWeaver::Job
{
public:
	LoadPackageKeywordsJob() = default;

	void impl( DbConnection* conn ) {
		// Collect all mask dependatoms
		QStringList linesPackage = recursiveRead( KurooConfig::defaultFilePackageKeywords() );

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

		//setStatus( "PackageKeywords", i18n("Collecting user package keywords...") );
		KurooDBSingleton::Instance()->singleQuery(	QStringLiteral("CREATE TEMP TABLE packageKeywords_temp ( "
													"idPackage INTEGER UNIQUE, "
													"keywords VARCHAR(255) );")
													, conn);

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

		QStringListIterator it( linesPackage );
		while (it.hasNext()) {
			QString trimmed = it.next().trimmed();

			if( !trimmed.startsWith( u'#' ) && !trimmed.isEmpty() ) {
				// set the atom string
				QString package = trimmed.section(u' ', 0, 0);

				PortageAtom atom( package );
				if ( atom.isValid() ) {
					auto commentStartIndex = trimmed.indexOf(u'#');
					// extract this line's keywords
					QString keywords = trimmed.left(commentStartIndex).section(u' ', 1).split(u' ', Qt::SkipEmptyParts).join(u' ');
					// QString keywords;
					// QStringList tokens = trimmed.split(u' ', Qt::SkipEmptyParts);
					// QStringList::iterator tokenIterator = tokens.begin();
					// ++tokenIterator;
					// while ( tokenIterator != tokens.end() ) {
					// 	keywords += *tokenIterator + u' ';
					// 	++tokenIterator;
					// }
					if ( keywords.isEmpty() )
						keywords = u'~' + KurooConfig::arch();

					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("Load package keywords: Can not find id in database for package %1/%2.")
						.arg( atom.category(), atom.package() );
					else
						KurooDBSingleton::Instance()->insert( QStringLiteral(
							"INSERT INTO packageKeywords_temp (idPackage, keywords) VALUES ('%1', '%2');" )
										.arg( id, keywords ), conn );
				}
				else
					qWarning() << QStringLiteral("Parsing package.keywords. Can not match package %1 in %2.").arg( trimmed,
						KurooConfig::defaultFilePackageKeywords() );
			}

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

		// Move content from temporary table to installedPackages
		KurooDBSingleton::Instance()->singleQuery( QStringLiteral("DELETE FROM packageKeywords;"), conn );
		KurooDBSingleton::Instance()->insert( QStringLiteral("INSERT INTO packageKeywords SELECT * FROM packageKeywords_temp;"), conn );
		KurooDBSingleton::Instance()->singleQuery( QStringLiteral("DROP TABLE packageKeywords_temp;"), conn );
	}

	void run( ThreadWeaver::JobPointer, ThreadWeaver::Thread* ) override {
		qDebug() << "Updating KEYWORDS DATABASE !!!!";
		DEBUG_LINE_INFO;

		DbConnection* const conn = KurooDBSingleton::Instance()->getStaticDbConnection();
		impl( conn );
		KurooDBSingleton::Instance()->returnStaticDbConnection( conn );
		//setStatus( "PackageKeywords", i18n("Done.") );
		PortageFilesSingleton::Instance()->refresh( PACKAGE_KEYWORDS_SCANNED );
	}
	Q_DISABLE_COPY(LoadPackageKeywordsJob)
};
