<?php
	require_once( $GLOBALS["site_root"] . "/includes/tasks/GeneralTask.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/CreditCard.inc.php" );


	class FinishUnfinishedTransactionsTask extends GeneralTask {

		public function __construct( $task_id , $task_processor ) {
			parent::__construct( $task_id , $task_processor );
			$this->ccm = new CreditCardModel();
		}
		
		protected function processTransaction( $cc_tran_id ) {
			$this->ccm->finishTransaction( $cc_tran_id );
		}
		
		protected function processFUTTask() {
			if ($this->task_processor->timeLeft()<3) return false;

			$this->tm->clearErrorHandler();	// buzi hack

			$ts = $this->tm->getTaskState();

			if (!isset( $ts["number_of_transactions"] )) {
				$number_of_transactions = $this->ccm->getNumberOfUnfinishedTransactions();
				$ts["number_of_transactions"]=$number_of_transactions;
				$ts["offset"]=0;
			}

			$cc_tran_ids = $this->ccm->getUnfinishedTransactionIds( $ts["offset"] , $ts["number_of_transactions"]-$ts["offset"] );
			// FNTHLog::logMessage( sprintf( "unfinished_transactions: %s" , FNTH_da( $cc_tran_ids , false , true ) ) );
			if (!empty( $cc_tran_ids )) {
				foreach ($cc_tran_ids as $cc_tran_id) {
					if ($this->task_processor->timeleft()<3) return false;
					$this->processTransaction( $cc_tran_id );
					$ts["offset"]++;
					$this->tm->setTaskState( $ts );
					$this->tm->updateTask();
					// usleep( 10000 );
				}
			}
			$this->tm->setErrorHandler();	// buznyak hack
			return true;
		}

		
		public function processTask() {
			$success = $this->processFUTTask();
			if ($success)
				$this->tm->closeTask();
			else
				$this->tm->releaseTask();
			return;
		}


	}


?>
