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

#include "lex_headers.h"
#include "UnigramDictionary.h"

namespace LexicalUnits
{
	UnigramDictionary* UnigramDictionary::m_pInstance = NULL;

	UnigramDictionary::UnigramDictionary()
	{}

	UnigramDictionary::~UnigramDictionary()
	{
		Clear();
	}

	size_t UnigramDictionary::AddLexicalUnit(LexicalUnitPtr lu)
	{
		size_t id = lu->GetId();
		m_mapIdToLexicalUnit[id] = lu;
		size_t & count = m_mapIdToCount[id];
		count++;
		return count;
	}

	size_t UnigramDictionary::GetCount(LexicalUnitPtr lu)
	{
		size_t id = lu->GetId();
		return m_mapIdToCount[id];
	}

	void UnigramDictionary::AddNewLexicalUnit(LexicalUnitPtr lu)
	{
		size_t id = lu->GetId();
		m_mapIdToLexicalUnit[id] = lu;
		if( m_mapIdToCount.find(id) != m_mapIdToCount.end() )
			m_mapIdToCount.erase(id);
	}

	size_t UnigramDictionary::RemoveLexicalUnit(LexicalUnitPtr lu)
	{
		size_t id = lu->GetId();
		size_t count = m_mapIdToCount[id];
		m_mapIdToLexicalUnit.erase(id);
		m_mapIdToCount.erase(id);
		return count;
	}

	void UnigramDictionary::Clear()
	{
		m_mapIdToLexicalUnit.clear();
		m_mapIdToCount.clear();
	}

	UnigramDictionary* UnigramDictionary::GetInstance()
	{
		if ( m_pInstance == NULL )
			m_pInstance = new UnigramDictionary();

		return m_pInstance;
	}

	void UnigramDictionary::Save(std::string filename)
	{
		std::ofstream file(filename.c_str());
		if(!file)
			throw std::runtime_error("Cannot open file: " + filename);

		Corpus::CWordDictionary *dict = Corpus::CWordDictionary::GetInstance();

		for(std::map<size_t, LexicalUnitPtr>::iterator iter = m_mapIdToLexicalUnit.begin(); iter != m_mapIdToLexicalUnit.end(); iter++)
		{
			file << Corpus::CTag::GetFlexClassString(iter->second->GetFlexClass()) << ":" << dict->GetAt( iter->second->GetBaseId() )
				<< ":= " << m_mapIdToCount[iter->first] << std::endl;
		}
	}
}


