var dynamsoft = Dynamsoft;
var arySelectedAreas = [], CurrentPath, CurrentPathName = unescape(location.pathname),
    CurrentPath = CurrentPathName.substring(0, CurrentPathName.lastIndexOf("/") + 1), strHTTPServer = location.hostname, strActionPage;
	
var OCRLanguages = [
	{ desc: "English", val: "en" },
	{ desc: "French", val: "fr" },
	{ desc: "German", val: "de" },
	{ desc: "Italian", val: "it" },
	{ desc: "Spanish", val: "es" },
	{ desc: "Portuguese", val: "pt" }
],
OCROutputFormat = [
	{ desc: "TXT", val: Dynamsoft.DWT.EnumDWT_OCRKitOutputFormat.TEXT },
	{ desc: "Text PDF", val: Dynamsoft.DWT.EnumDWT_OCRKitOutputFormat.PDF_PLAIN_TEXT },
	{ desc: "Image-over-text PDF", val: Dynamsoft.DWT.EnumDWT_OCRKitOutputFormat.PDF_WITH_EXTRA_TEXTLAYER }
],
PageOrientation = [
	{ desc: "Auto", val: Dynamsoft.DWT.EnumDWT_PageOrientation.AUTO },
	{ desc: "0 degrees", val: Dynamsoft.DWT.EnumDWT_PageOrientation.ANGLE_0 },
	{ desc: "90 degrees", val: Dynamsoft.DWT.EnumDWT_PageOrientation.ANGLE_90 },
	{ desc: "180 degrees", val: Dynamsoft.DWT.EnumDWT_PageOrientation.ANGLE_180 },
	{ desc: "270 degrees", val: Dynamsoft.DWT.EnumDWT_PageOrientation.ANGLE_270 }
], DetectionModels = [], RecognitionModels= [];

function isWindows64Bit() {
  const ua = navigator.userAgent.toLowerCase();
  const platform = navigator.platform.toLowerCase();
  const isWindows = platform.indexOf("win") >= 0;
  const is64bit = ua.indexOf("win64") >= 0 
               || ua.indexOf("wow64") >= 0 
               || ua.indexOf("x64") >= 0 
               || ua.indexOf("amd64") >= 0;

  return isWindows && is64bit;
}

window.onload = function() {
	if (isWindows64Bit()) {
	  Dynamsoft.DWT.Load();
	} else {
	  alert('The OCR feature is only supported on x64 versions of Windows.');
	}
};

	
// Check if the control is fully loaded.
Dynamsoft.DWT.RegisterEvent("OnWebTwainReady", function() {
    DWTObject = Dynamsoft.DWT.GetWebTwain('dwtcontrolContainer');  
    if (DWTObject) {
		DWTObject.Viewer.width = 504;
	    DWTObject.Viewer.height = 599;
		
		if (!Dynamsoft.Lib.env.bWin  || !Dynamsoft.dcp.b64bit) {
			Dynamsoft.DWT.ShowMessage('The OCR feature is only supported on x64 versions of Windows.', {
				width: 580,
				headerStyle: 2
			});
			
			var btnOCR = document.getElementById("btnOCR");
			btnOCR.disabled = true;
			
			var btnSave = document.getElementById("btnSave");
			btnSave.disabled = true;
			return;
	   }
		
		// from v19.0
		DWTObject.Addon.PDF.SetReaderOptions({
			convertMode: Dynamsoft.DWT.EnumDWT_ConvertMode.CM_RENDERALL,
			renderOptions: {
				renderAnnotations: true,
				resolution: 200
			},
			preserveUnmodifiedOnSave: true
		});
				
	    DWTObject.Viewer.on("pageAreaSelected", Dynamsoft_OnImageAreaSelected);
	    DWTObject.Viewer.on("pageAreaUnselected", Dynamsoft_OnImageAreaDeselected);
		
		var i;
		for (i = 0; i < OCRLanguages.length; i++)
			document.getElementById("ddlLanguages").options.add(new Option(OCRLanguages[i].desc, i));
		for (i = 0; i < OCROutputFormat.length; i++)
			document.getElementById("ddlOCROutputFormat_Save").options.add(new Option(OCROutputFormat[i].desc, i));
		document.getElementById("ddlLanguages").selectedIndex = 0;
		for (i = 0; i < PageOrientation.length; i++)
			document.getElementById("ddlPageOrientation").options.add(new Option(PageOrientation[i].desc, i));
		document.getElementById("ddlPageOrientation").selectedIndex = 1;

		DWTObject.Addon.OCRKit.GetInstalledOCRInfo().then(function(){
			
		}).catch(function(){
			//Download OCR
			downloadOCR();
		});

	}
});

function setLanguagesEnable(){
	var ddlLanguages = document.getElementById("ddlLanguages");
	var ddlOCRRecognitionMode = document.getElementById("ddlOCRRecognitionMode");
	if(ddlOCRRecognitionMode.selectedIndex == 0) {
		ddlLanguages.disabled = false;
	} else {
		ddlLanguages.disabled = true;
	}
}

function downloadOCR() {
	if (Dynamsoft.Lib.product.bChromeEdition) {
		var ObjString = [];
		ObjString.push('<div class="p15">');
		ObjString.push('The <strong>OCR Module</strong> is not installed on this PC.<br />Please click the button below to download and unzip the file, double-click to run <strong>Install.cmd</strong>, and then refresh this page.');
		ObjString.push('<p class="tc mt15 mb15"><a style="color: #ffffff;" class="btn lgBtn bgBlue" href="https://download2.dynamsoft.com/dwt/DynamicWebTWAINOCRPack.zip">Download</a><hr /></p>');
		ObjString.push('<i><strong>The installation is a one-time process</strong> <br />It might take some time depending on your network.</i>');
		ObjString.push('</div>');
		Dynamsoft.DWT.ShowMessage(ObjString.join(''), {
			width: 480,
			headerStyle: 1,
			backgroundStyle: 1
		});
		
	} else {
		alert('Your browser is not supported');
	}
}

function Dynamsoft_OnImageAreaSelected(index, rect) {
	if (rect.length > 0) {
		arySelectedAreas = [];
		for(var i=0; i< rect.length; i++){
			var currentRect = rect[i];
			arySelectedAreas.push(index, currentRect);
		}
	}
}

function Dynamsoft_OnImageAreaDeselected(index) {
	arySelectedAreas = [];
}

function AcquireImage() {
	if (DWTObject) {
		DWTObject.SelectSource(function () {
			var OnAcquireImageSuccess, OnAcquireImageFailure;
			OnAcquireImageSuccess = OnAcquireImageFailure = function () {
				DWTObject.CloseSource();
			};
			DWTObject.OpenSource();
			DWTObject.IfDisableSourceAfterAcquire = true;
			DWTObject.AcquireImage(OnAcquireImageSuccess, OnAcquireImageFailure);
		}, function () {
			console.log('SelectSource failed!');
		});
	}
}

function LoadImages() {
	if (DWTObject) {

		DWTObject.LoadImageEx('', 5,
			function () {
			},
			function (errorCode, errorString) {
				alert('Load Image:' + errorString);
			}
		);
	}
}

function DoOCR() {
	if (DWTObject) {
		if (DWTObject.HowManyImagesInBuffer == 0) {
			alert("Please scan or load an image first.");
			return;
		}
		
		var setting = {
			pageOrientation: PageOrientation[document.getElementById("ddlPageOrientation").selectedIndex].val,
			language: OCRLanguages[document.getElementById("ddlLanguages").selectedIndex].val
		};
		
		var rects = [];
		if(arySelectedAreas.length > 0){
			for(var i= 0; i< arySelectedAreas.length; i++){
				var selectedArea = arySelectedAreas[i];
				if (typeof selectedArea !== "object" || selectedArea === null) continue;
				if(selectedArea.x !=0 || selectedArea.y != 0 || selectedArea.width != 0 || selectedArea.height != 0)
					//rects.push(selectedArea);
				rects.push({left: selectedArea.x, top: selectedArea.y, right: selectedArea.x + selectedArea.width, bottom: selectedArea.y + selectedArea.height});
			}
			
		}
		
		DWTObject.Addon.OCRKit.Recognize(
		   DWTObject.CurrentImageIndexInBuffer,
		   {settings: setting, 
		   rects: rects}
		).then(function(result){
			if (result == null)
				return null;
			if (result.code && result.code !== 0) {
				alert(result.message);
				//alert("OCR result is Null.");
				return;
			} else {
				var bRet = ['<p>'];
				for (var i = 0; i < result.blocks.length; i++) {
					var _resultblock = result.blocks[i];
					for (var j = 0; j < _resultblock.lines.length; j++) {
						var _line = _resultblock.lines[j];
						for (var k = 0; k < _line.words.length; k++) {
							var _word = _line.words[k];
							var strTemp = _word.value;
							strTemp = strTemp.replace(/</g, "&lt;");
							bRet.push(strTemp + ' ');
						}
						bRet.push('<br />');
					}
				}
				bRet.push('</p>');
				document.getElementById('div-ocrresult').innerHTML = bRet.join(''); 
			}
		}).catch(function(exp){
			alert(exp.message);
		});	
	}
}


function RemoveSelected() {
    if (DWTObject) {
        DWTObject.RemoveAllSelectedImages();
    }
}

function SaveSelected(){
	if (DWTObject) {
		var OCROutputFormatValue = OCROutputFormat[document.getElementById("ddlOCROutputFormat_Save").selectedIndex].val;
		var fileName = "DynamicWebTWAIN.pdf";
		if(OCROutputFormatValue == Dynamsoft.DWT.EnumDWT_OCRKitOutputFormat.TEXT)
		{
			fileName = "DynamicWebTWAIN.txt";
		}
        DWTObject.Addon.OCRKit.SaveToPath(DWTObject.SelectedImagesIndices,OCROutputFormatValue, fileName).then(function(result){
			console.log(result);
		}).catch(function(exp){
			alert(exp.message);
		})
		
    }
}

