<?php
//require_once 'loginCheckPoint.php';
require_once 'parseUtils.php';

if ($argv[1] != "invokedFromBatch")
	die("This operation cannot be invoked.");

$docExRunning = true;
$mysqli = sqlCreateConnection("extractNamesNoEmail");
$userName = $mysqli->real_escape_string($userdetails[Username]);
//select last email inserted to name_alternatives
$res = sqlQuery($mysqli, "SELECT personId FROM name_alternatives WHERE personTable = 'email' ORDER BY personId DESC LIMIT 1");
if (!$res)
{
	write_to_log("ERROR", "failed to select last email");
	die();
}
$row = $res->fetch_object();
$lastEmail = $row? $row->personId : 0;
do {
	do {
		$numEmails = 0;
		//select next 100 emails
		$nextEmailsRes = sqlQuery($mysqli, "SELECT * FROM (SELECT id, name, username FROM email WHERE id > $lastEmail ORDER BY id DESC LIMIT 100) AS t ORDER BY t.id ASC");
		while ($nextEmailsRes && $row = $nextEmailsRes->fetch_object())
		{
			$email = $row->name;
			$email = explode("@", $email);
			$email = $email[0];
			$email = str_replace(array(".", "-"), " ", $email);
			$personKey2idName = array();
			$name2additionalInfo = array();
			analyzeAndPopulateNAs($mysqli, $email, $personKey2idName, $name2additionalInfo);
			foreach ($personKey2idName as $key => $idName)
				$personKey2idName[$key]["id"] = $row->id;
			
			//insert name additional info to DB
			insertNaAdditionalInfoToDB($name2additionalInfo, $mysqli);
			$watchListName = "DOCEX Entities DB";
			//insert all NAs to DB
			insertNAsToDB($mysqli, $personKey2idName, "email", $watchListName, $userName);
			$lastEmail = $row->id;
			$numEmails++;
		}
	}
	while ($numEmails);
	
	if (!$docExRunning)
		break;

	//if no new emails, but still running - wait for new emails (sleep 3 secs)
	sleep(3);
	
	//retry as long as intuScan is running (new emails might be added), then try once more
	$res = sqlQuery($mysqli, "SELECT isRunning FROM user_status WHERE isRunning = 1");
	$docExRunning = $res && $res->num_rows;
}
while (true);

?>