<?php
	require_once( $GLOBALS["site_root"] . "/includes/tasks/GeneralTask.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/Members.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/Globals.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/Status.inc.php" );

	class StatusRegenTask extends GeneralTask {
		protected $mm;
		protected $membersm;
		protected $um;
		
		public function __construct( $task_id , $task_processor ) {
			parent::__construct( $task_id , $task_processor );
			$this->mm = new MemberModel();
			$this->membersm = new MembersModel();
			$this->um = new UserModel();
			$this->sm = new StatusModel();
		}

		protected function newMemberStatus( $member ) {
			return $this->sm->getNewMemberStatus( $member );
		}

		protected function processMember( $member_id ) {
			$member = $this->mm->getMemberFromMemberId( $member_id );
			$user = $this->um->getUserFromUserId( $member["user_id"] );
			$new_status = $this->newMemberStatus( $member );
			if ($member["current_status"]==$new_status) return;

			switch ($new_status) {
			case STATUS_NEW_USER_EXPIRED_TOTAL:
			case STATUS_EXPIRED_TOTAL:
				$activate_resend = false;
				break;
			default:
				$activate_resend = true;
				break;
			}
			$this->mm->updateMemberStatus( $member_id , $new_status , $activate_resend );
			$this->mm->setMemberDirty( $member_id , true ); // statusz generalaskor fut neki egy dirtyzes
			$this->task_processor->log(
				sprintf( "%s (#%d/%s) status modified (%s => %s)",
					$user["email"],
					$member["member_id"],
					$member["member_username"],
					$member["current_status"],
					$new_status )
			);
		}

		protected function processStatusRegenTask() {
			if ($this->task_processor->timeLeft()<3) return false;
			$ts = $this->tm->getTaskState();

			if (!isset( $ts["number_of_members"] )) {
				$numofmembers = $this->membersm->getNumberOfMembers();
				$ts["number_of_members"]=$numofmembers;
				$ts["offset"]=0;
			}


			$member_ids = $this->membersm->getMemberids( $ts["offset"] , $ts["number_of_members"]-$ts["offset"] );
			if (!empty( $member_ids )) {
				foreach ($member_ids as $member_id) {
					if ($this->task_processor->timeleft()<3) return false;
					$this->processMember( $member_id );
					$ts["offset"]++;
					$this->tm->setTaskState( $ts );
					$this->tm->updateTask();
					// usleep( 10000 );
				}
			}
			return true;
		}


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

?>
