<?php
class MailerEmailQueueProcessor extends EmailQueueProcessor {


	public $_recordLimit = 15;
	private $_mailerContent;
	private $_mailerContentFilter;

	public function init() {
		
		echo 1;
		
		parent::init();
		
		Dev::pm($this->pendingEmailQueueGroup);
		
		if($this->pendingEmailQueueGroup === null)
			return;
	
		echo $this->pendingEmailQueueGroup->id;

		$this->_mailerContentFilter = MailerContentContactFilter::model()->find(array(
			'condition' => 'email_queue_group_id=:group_id AND status=:status',
			'params' => array(
				':group_id' => $this->pendingEmailQueueGroup->id,
				':status' => MailerContentContactFilter::STATUS_DONE
			)
		));

		
		Dev::pm($this->_mailerContentFilter);
		if($this->_mailerContentFilter === null)
			return;
			// throw new Exception("MailerEmailQueueProcessor cannot run. MailerContentFilter is null.", 1);
			
		echo 2;
		
		$this->_mailerContent = $this->_mailerContentFilter->mailerContent;

		if($this->_mailerContent === null)
			throw new Exception("MailerEmailQueueProcessor cannot run. _mailerContent is null.", 1);	
		
		
	}

	public function run() {
		
		
		// echo 1;
		
		// var_dump($this->_mailerContentFilter);
		
		if($this->_mailerContentFilter === null)
			return;
		else
			echo 'Failed to run';
		
		
		
		parent::run();

	}

	public function sendOutEmail($contact) {

		$mailerContact = EmailContact::model()->findByPk($contact->email_contact_id);

		$contact->setSending(true);

		$res = $this->_mailerContent->sendOutEmail($mailerContact, MailerContentTracking::TYPE_LIVE_DATA);

		if($res['sendResult']){

			$contact->setSent(true);

		}
		else
			$contact->setError(true);


	}

	public function checkStats() {

		$totalContacts = $this->pendingEmailQueueGroup->getContactCount();
		$contactsSent = $this->pendingEmailQueueGroup->getSentCount();
		$contactsError = $this->pendingEmailQueueGroup->getErrorCount();


		var_dump('total: '.$totalContacts.' = sent:'.$contactsSent.' + error:'.$contactsError);

		return ($this->_mailerContentFilter->isDone && (((int)$contactsSent + (int)$contactsError) >= (int)$totalContacts));


	}

	public function setEmailQueueGroupDone() {

		parent::setEmailQueueGroupDone();

	}

}