/*
    Copyright (C) 2012 Bartosz Broda, Jacek Bochenek, Łukasz Biłeńkij, 
    Damian Jaworski, Wojciech Mazur, Dominik Piasecki, Maciej Piasecki, 
    Radosław Ramocki
    
    This program is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 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 LICENSE and COPYING files for more details.
*/

#ifndef ARCHITECT_DOC_TERM_ARCHITECT_H
#define ARCHITECT_DOC_TERM_ARCHITECT_H

#include "matrices_all.h"
#include <boost/thread/mutex.hpp>
#include <mpi.h>
#include "../mpi_handler/mpi_handler.h"
#include "Corpus/Corpus/corpus_all.h"
#include "LexicalUnit.h"
#include <poliqarp_reader/PoliqarpSentencer.h>
#include <poliqarp_reader/PoliqarpReader.h>

namespace doc_term_architect
{
	const int GIVE_JOB = -150000;
	const int EXIT_CODE = -150001;
	const int SENDING_RESULTS = -150002;
	class DocTermArchitectMaster
	{
	public:
		DocTermArchitectMaster();
		void Start();
		void Finalize();
	private:
		void sendJob(int nodeNum);
		void receiveResults(int nodeNum);
		int numOfJobs;
		int jobsFinished;
		int jobIterator;
		parallel::MPI_Handler mpiHandler;
		std::vector<Matrices::CompressedVectorPtr> *results;
		std::vector<std::string> rowLabels;
		int numOfColumns;
		int tokenCounter;

	};
	class DocTermArchitectSlave
	{
	public:
		DocTermArchitectSlave();
		void Start();
	private:
		void sendResults();
		int fetchJob();
		void processDocument(int docNum);
		void processCorpus(int corpusNum);
		std::vector<Corpus::CToken*> FlattenDocument(std::vector< boost::shared_ptr<Corpus::CSentence> > * pSentences);
		void processToken(Corpus::CToken *token,Matrices::CompressedVectorPtr &document_vector );
		bool exitFlag;
		int tasksDone;
		parallel::MPI_Handler mpiHandler;
		std::vector<std::string> rowLabels;
		std::vector<Matrices::CompressedVectorPtr> results;
		int m_stTokenCount;

	};

	class DocTermMatrixBuilder
	{
	public:
		//
		DocTermMatrixBuilder(std::vector<size_t> documents, Matrices::CRSMatrixPtr pMatrix);
		void operator() ();
		size_t GetTokenCount();
	private:
		Matrices::CRSMatrixPtr m_pMatrix;
		std::vector<size_t> m_vMyDocuments;
		int m_iThreadNo;
		static int thread_counter;
		size_t m_stTokenCount;
		static boost::mutex cout_mutex;

	};
}//namespace doc_term_architect

#endif //ARCHITECT_DOC_TERM_ARCHITECT_H

