#include "GoogleOcrWrapper.h"
#include "GoogleOcr.h"
#include "Dictionary.h"
#include "ChipMonkUtilities.h"
#include "ChipMonkTypes.h"

CGoogleOcr::~CGoogleOcr(void) {
}

bool CGoogleOcr::Init() {
	m_bCancel = FALSE;
	return TessDllInit(CHIPMONK_INSTALL_DIRECTORY, "eng") != NULL;
}

void CGoogleOcr::ShutDown() {
	TessDllRelease();
}

bool AddToTextPage(const ETEXT_DESC *output, COcrTextPage & textPage){
	if(!output || output->count < 1) {
		return false;
	}
	textPage.AddRegion(CRect(0, 0, 0, 0));
	textPage.AddLineToLastRegion(CRect(0, 0, 0, 0));
	textPage.AddWordToLastLine(CRect(0, 0, 0, 0));
	int nRight = 0;
	UINT nFeatures(0);
	for (int i = 0; i < output->count; ++i) {
		const EANYCODE_CHAR* ch = output->text + i;
		if(ch->right < nRight) {
			textPage.AddLineToLastRegion(CRect(0, 0, 0, 0));
			textPage.AddWordToLastLine(CRect(0, 0, 0, 0));
		}
		else if(ch->blanks > 0) {
			textPage.AddWordToLastLine(CRect(0, 0, 0, 0));
		}
		textPage.AddCharacterToTheLastWord(ch->char_code, 
				CRect(ch->left, ch->top, ch->right, ch->bottom),
				ch->confidence * 3,
				nFeatures);
		nRight = ch->right;
	}
	return true;
}

bool CGoogleOcr::Recognize(UCHAR* imgBuffer, int nWidth, int nHeight, COcrTextPage& textPage) {
	WriteStringToLog("Google Recognition Begin\n");
	TessDllBeginPageUprightBPP(nWidth, nHeight, imgBuffer, "eng", 1);
	WriteStringToLog("Google TessDllBeginPageUprightBPP Done\n");
	const ETEXT_DESC* output = TessDllRecognize_all_Words();
	WriteStringToLog("Google Recognition Done\n");
	if(!output){
		return false;
	}
	if(!AddToTextPage(output, textPage)){
		return false;
	}
	TessDllEndPage();
	if(m_bCancel)
		return true;
	WriteStringToLog("Dictionary::Instance\n");
	Dictionary *pDict = Dictionary::Instance();
	WriteStringToLog("Dictionary::Instance Done\n");
	textPage.SetLineConfidences(pDict);
	WriteStringToLog("SetLineConfidences Done\n");
	if(m_bCancel)
		return true;
	textPage.AddTextFeatureToRegions(COMPLETELY_OCRED);
	if(textPage.GetTextFeature(WHITE_ON_BLACK)){
		textPage.AddTextFeatureToRegions(WHITE_ON_BLACK);
	}
	WriteStringToLog("Recognize Done\n");
	return true;
}
