<?php
/*********************************************************************************
 * The contents of this file are subject to the TimeTrex Public License Version
 * 1.1.0 ("License"); You may not use this file except in compliance with the
 * License. You may obtain a copy of the License at http://www.TimeTrex.com/TPL
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied.  See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * All copies of the Covered Code must include on each user interface screen:
 *    (i) the "Powered by TimeTrex" logo and
 *    (ii) the TimeTrex copyright notice
 * in the same form as they appear in the distribution.  See full license for
 * requirements.
 *
 * The Original Code is: TimeTrex Open Source
 * The Initial Developer of the Original Code is TimeTrex Payroll Services
 * Portions created by TimeTrex are Copyright (C) 2004-2007 TimeTrex Payroll Services;
 * All Rights Reserved.
 *
 ********************************************************************************/
/*
 * $Revision: 1908 $
 * $Id: UserGroupFactory.class.php 1908 2008-06-06 17:52:02Z ipso $
 * $Date: 2008-06-06 10:52:02 -0700 (Fri, 06 Jun 2008) $
 */

/**
 * @package Module_Users
 */
class UserGroupFactory extends Factory {
	protected $table = 'user_group';
	protected $pk_sequence_name = 'user_group_id_seq'; //PK Sequence name

	protected $fasttree_obj = NULL;

	protected $tmp_data = array();
	function getFastTreeObject() {

		if ( is_object($this->fasttree_obj) ) {
			return $this->fasttree_obj;
		} else {
			global $fast_tree_user_group_options;
			$this->fasttree_obj = new FastTree($fast_tree_user_group_options);

			return $this->fasttree_obj;
		}
	}

	function getCompany() {
		if ( isset($this->data['company_id']) ) {
			return $this->data['company_id'];
		}

		return FALSE;
	}
	function setCompany($id) {
		$id = trim($id);

		Debug::Text('Company ID: '. $id, __FILE__, __LINE__, __METHOD__,10);
		$clf = new CompanyListFactory();

		if ( $this->Validator->isResultSetWithRows(	'company',
													$clf->getByID($id),
													TTi18n::gettext('Company is invalid')
													) ) {

			$this->data['company_id'] = $id;

			return TRUE;
		}

		return FALSE;
	}

	//Use this for completly editing a row in the tree
	//Basically "old_id".
	function getPreviousParent() {
		if ( isset($this->tmp_data['previous_parent_id']) ) {
			return $this->tmp_data['previous_parent_id'];
		}

		return FALSE;
	}
	function setPreviousParent($id) {

		$this->tmp_data['previous_parent_id'] = $id;

		return TRUE;
	}

	function getParent() {
		if ( isset($this->tmp_data['parent_id']) ) {
			return $this->tmp_data['parent_id'];
		}

		return FALSE;
	}
	function setParent($id) {

		$this->tmp_data['parent_id'] = $id;

		return TRUE;
	}

	function getName() {
		return $this->data['name'];
	}
	function setName($name) {
		$name = trim($name);
		if (	$this->Validator->isLength(	'name',
											$name,
											TTi18n::gettext('Name is invalid'),
											2,50)
						) {

			$this->data['name'] = $name;

			return TRUE;
		}

		return FALSE;
	}

	function Validate() {

		if ( $this->isNew() == FALSE
				AND $this->getId() == $this->getParent() ) {
				$this->Validator->isTrue(	'parent',
											FALSE,
											TTi18n::gettext('Cannot re-parent group to itself')
											);
		} else {
			if ( $this->isNew() == FALSE ) {
				$this->getFastTreeObject()->setTree( $this->getCompany() );
				//$children_ids = array_keys( $this->getFastTreeObject()->getAllChildren( $this->getID(), 'RECURSE' ) );

				$children_ids = $this->getFastTreeObject()->getAllChildren( $this->getID(), 'RECURSE' );
				if ( is_array($children_ids) ) {
					$children_ids = array_keys( $children_ids );
				}
				
				if ( is_array($children_ids) AND in_array( $this->getParent(), $children_ids) == TRUE ) {
					Debug::Text(' Objects cant be re-parented to their own children...' , __FILE__, __LINE__, __METHOD__,10);
					$this->Validator->isTrue(	'parent',
												FALSE,
												TTi18n::gettext('Unable to change parent to a child of itself')
												);
				}
			}
		}

		return TRUE;
	}

	function preSave() {
		if ( $this->isNew() ) {
			Debug::Text(' Setting Insert Tree TRUE ', __FILE__, __LINE__, __METHOD__,10);
			$this->insert_tree = TRUE;
		} else {
			Debug::Text(' Setting Insert Tree FALSE ', __FILE__, __LINE__, __METHOD__,10);
			$this->insert_tree = FALSE;
		}

		return TRUE;
	}


	//Must be postSave because we need the ID of the object.
	function postSave() {

		$this->StartTransaction();

		$this->getFastTreeObject()->setTree( $this->getCompany() );

		if ( $this->getDeleted() == TRUE ) {
			//FIXME: Get parent of this object, and re-parent all groups to it.
			$parent_id = $this->getFastTreeObject()->getParentId( $this->getId() );

			//Get items by group id.
			$ulf = new UserListFactory();
			$ulf->getByCompanyIdAndGroupId( $this->getCompany(), $this->getId() );
			if ( $ulf->getRecordCount() > 0 ) {
				foreach( $ulf as $obj ) {
					Debug::Text(' Re-Grouping Item: '. $obj->getId(), __FILE__, __LINE__, __METHOD__,10);
					$obj->setGroup($parent_id);
					$obj->Save();
				}
			}

			$this->getFastTreeObject()->delete( $this->getId() );

			$this->CommitTransaction();

			return TRUE;
		} else {

			$retval = TRUE;
			//if ( $this->getId() === FALSE ) {
			if ( $this->insert_tree === TRUE ) {
				Debug::Text(' Adding Node ', __FILE__, __LINE__, __METHOD__,10);

				//echo "Current ID: ".  $this->getID() ."<br>\n";
				//echo "Parent ID: ".  $this->getParent() ."<br>\n";

				//Add node to tree
				if ( $this->getFastTreeObject()->add( $this->getID(), $this->getParent() ) === FALSE ) {
					Debug::Text(' Failed adding Node ', __FILE__, __LINE__, __METHOD__,10);

					$this->Validator->isTrue(	'name',
												FALSE,
												TTi18n::gettext('Name is already in use')
												);
					$retval = FALSE;
				}
			} else {
				Debug::Text(' Editing Node ', __FILE__, __LINE__, __METHOD__,10);

				//Edit node.
				$retval = $this->getFastTreeObject()->move( $this->getID() , $this->getParent() );
			}

			if ( $retval === TRUE ) {
				$this->CommitTransaction();
			} else {
				$this->FailTransaction();
			}

			return $retval;
		}
	}

	function addLog( $log_action ) {
		return TTLog::addEntry( $this->getId(), $log_action, TTi18n::getText('Employee Group'), NULL, $this->getTable() );
	}

}
?>
