<?php
	require_once( $GLOBALS["site_root"] . "/includes/tasks/GeneralTask.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/Job.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/Member.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/User.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/TemplateMail.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/SystemParameters.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/Constants.inc.php" );

	class JobTask extends GeneralTask {
		protected $jm;
		protected $mm;
		protected $um;

		public function __construct( $task_id , $task_processor ) {
			parent::__construct( $task_id , $task_processor );
			$this->jm = new JobModel();
			$this->mm = new MemberModel();
			$this->um = new UserModel();
		}
		
		protected function addMemberToJob( $member_id , $job_id ) {
			$ins = array();
			$ins["job_id"]=$job_id;
			$ins["member_id"]=$member_id;
			FNTH_db_free_result( FNTH_db_query(
			FNTH_db_generate_insert_query( "job_notifications" , $ins ) ) );
		}	

		protected function processActivationTask() {
			if ($this->task_processor->timeLeft()<3) return false;	// mindjart lejar az ido


			$job_id = $this->tm->getTaskUID();
			$job = $this->jm->getJobFromId( $job_id , true );

			$ts = $this->tm->getTaskState();
			$where_clause = " where notifications<>'no'";
			if (!isset( $ts["number_of_recipients"] )) {
				$query = sprintf( "delete from job_notifications where job_id=%d" , $job_id );
				FNTH_db_free_result( FNTH_db_query( $query ) );

				$numofitems = FNTH_db_get_field(
					sprintf( "select count(*) as num from members %s",$where_clause),"num" );
				$ts["number_of_recipients"]=$numofitems;
				$ts["offset"]=0;
			}

			$batchsize = 100;
			$query = sprintf( "select * from members %s order by member_id limit %d offset %d",
				$where_clause,
				$batchsize,
				$ts["offset"] );
			$members = FNTH_db_get_resultset( $query );
			if (!empty( $members )) {
				foreach ($members as $member) {
					if ($this->task_processor->timeleft()<3) return false;
					if ($this->jm->isMemberJobRecipient( $member , $job ))
						$this->addMemberToJob( $member["member_id"] , $job_id );
					// usleep( 50000 );	// REMOVEME - just for testing
					$ts["offset"]++;
					$this->tm->setTaskState( $ts );
					$this->tm->updateTask();
				}
			}	
			if ($ts["offset"]==$ts["number_of_recipients"] || empty( $members )) {
				$this->jm->sendJob( $job_id );
				return true;
			}
			return false;
		}

		protected function sendNotification( $job_id , $member_id ) {
			$job = $this->jm->getJobFromId( $job_id , true );
			$member = $this->mm->getMemberFromMemberId( $member_id );

			switch ($member["current_status"]) {
			case STATUS_DELETED:
			case STATUS_NEW_USER_DELETED:
				// toroltek nem kapnak (bar ide elvileg nem jutunk el, de azert hatha
				break;
			default:
				$user = $this->um->getUserFromUserId( $member["user_id"] );

				// collect recipients
				$emails = array();
				switch ($member["use_email"]) {
				case "both":
					$emails[]=$user["email"];
					// direkt nincs letores
				case "fo":
					$emails[]=$member["member_username"]."@fordit.hu";
					break;
				default:
				case "own":
					$emails[]=$user["email"];
					break;
				}

				$emails = array_unique( $emails );
				if (!empty( $emails )) {
					foreach ($emails as $email) {
						$tmm = new TemplateMailModel( "sys_job_notification_to_translators" );
						// mantis #518
						$tmm->sReplyTo = $job["poster_name"];
						$tmm->sReplyToEmail = $job["poster_email"];
						$tmm->setHtml( true );
						$tmm->setPlain( true );
						$cm = new ConstantsModel( $tmm );
						$cm->addSystemParametersToTemplate();
						$cm->addJobConstantsToTemplate( $job["job_id"] , "job" , $job );
						$cm->addMemberConstantsToTemplate( $member["member_id"] , "member" , $member );
						$cm->addUserConstantsToTemplate( $member["user_id"] , "user" , $user );
						$tmm->sendMail( $email );
					}
				}
			}

			$query = sprintf( "update job_notifications set send_status='S',ststamp=now() where job_id=%d and member_id=%d" , $job_id , $member_id );
			FNTH_db_free_result( FNTH_db_query( $query ) );
		}

		protected function processNotificationTask() {
			if ($this->task_processor->timeLeft()<3) return false;	// lejar az ido
			$job_id = $this->tm->getTaskUID();
			
			$where_clause = sprintf( " where job_id=%d" , $job_id );
			$ts = $this->tm->getTaskState();
			if (!isset( $ts["number_of_recipients"] )) {
				// frissen indulos
				$numofitems = FNTH_db_get_field( sprintf( "select count(*) as num from job_notifications %s" , $where_clause ) , "num" );
				$ts["number_of_recipients"]=$numofitems;
				$ts["offset"]=0;
			}
			
			$batchsize = 100;

			$member_ids = FNTH_db_get_column(
				sprintf( "select member_id from job_notifications %s order by member_id
					limit %d offset %d",
					$where_clause,
					$batchsize,
					$ts["offset"] ) , "member_id" );
			if (!empty( $member_ids )) {
				foreach ($member_ids as $member_id) {
					if ($this->task_processor->timeleft()<3) return false;
					$this->task_processor->log(
						sprintf( "sending #%d job notification (%d/%d)",
						$job_id,$ts["offset"]+1,$ts["number_of_recipients"] ) );
					$this->sendNotification( $job_id , $member_id );
					// usleep( 100000 );		// REMOVEME
					$ts["offset"]++;

					$this->tm->setTaskState( $ts );
					$this->tm->updateTask();
				}
			}
			if ($ts["offset"]==$ts["number_of_recipients"] || empty( $member_ids )) {
				FNTH_db_free_result( FNTH_db_query( sprintf( "update jobs set is_sent=true,sent_at=now() where job_id=%d" , $job_id ) ) );
				return true;
			}
			$this->tm->lowerTaskPriority();
			$this->tm->updateTask();
			return false;
		}

		public function processTask() {
			$success = false;
			$task_type = $this->tm->getTaskType();
			switch ($task_type) {
			case "job_activation":
				$success = $this->processActivationTask();
				break;
			case "job_notification":
				$success = $this->processNotificationTask();
				break;
			}
			if ($success)
				$this->tm->closeTask();
			else
				$this->tm->releaseTask();
			return;
			/*
			$this->tm->getTaskId();
			return parent::processTask();
			*/
		}
	}

?>
