<?php

if (!defined('XOOPS_ROOT_PATH')) exit();

require_once XOOPS_TRUST_PATH . '/libs/xoonips/class/Enum.class.php';

/**
 * Xleprogress_ItemObject
**/
class Xleprogress_ItemObject extends XoopsSimpleObject
{
	public $mDirname = null;
	public $mHistory = array();
	public $mType = null;
	protected $_mHistoryLoadedFlag = false;

	/**
	 * __construct
	 * 
	 * @param	string	$dirname
	 * 
	 * @return	void
	**/
	public function __construct()
	{
		$this->initVar('item_id', XOBJ_DTYPE_INT, '', false);
		$this->initVar('title', XOBJ_DTYPE_STRING, '', false, 255);
		$this->initVar('type_id', XOBJ_DTYPE_INT, '', false);
		$this->initVar('target_id', XOBJ_DTYPE_INT, '', false);
		$this->initVar('uid', XOBJ_DTYPE_INT, 0, false);
		$this->initVar('step', XOBJ_DTYPE_INT, 0, false);
		$this->initVar('status', XOBJ_DTYPE_INT, Lenum_WorkflowStatus::PROGRESS, false);
		$this->initVar('revision', XOBJ_DTYPE_INT, 0, false);
		$this->initVar('url', XOBJ_DTYPE_TEXT, '', false);
		$this->initVar('posttime', XOBJ_DTYPE_INT, time(), false);
		$this->initVar('updatetime', XOBJ_DTYPE_INT, time(), false);
		$this->initVar('deletetime', XOBJ_DTYPE_INT, 0, false);
	}

	/**
	 * setFirstStep
	 * 
	 * @param	void
	 * 
	 * @return	void
	**/
	public function setFirstStep()
	{
		$approval = Legacy_Utils::getModuleHandler('approval', $this->getDirname())->getNextApproval($this->get('type_id'), 0);
		if($approval){
			$this->set('step', $approval->get('step'));
		}
		else{
			$this->set('step', 0);
			$this->set('status', Lenum_WorkflowStatus::FINISHED);
		}
	}

	/**
	 * incrementRevision
	 * 
	 * @param	void
	 * 
	 * @return	void
	**/
	public function incrementRevision()
	{
		$this->set('revision', $this->get('revision')+1);
	}

	/**
	 * loadHistory
	 * 
	 * @param	string	$order
	 * 
	 * @return	void
	**/
	public function loadHistory(/*** string ***/ $order='asc')
	{
		if ($this->_mHistoryLoadedFlag == false) {
			$handler = Legacy_Utils::getModuleHandler('history', $this->getDirname());
			$cri = new Criteria('item_id', $this->get('item_id'));
			$cri->setSort('posttime', $order);
			$this->mHistory =& $handler->getObjects($cri);
			$this->_mHistoryLoadedFlag = true;
		}
	}
	
	/**
	 * loadType
	 * 
	 * @param	string	$order
	 * 
	 * @return	void
	**/
	public function loadType()
	{
		if($this->mType == null){
			$this->mType = Legacy_Utils::getModuleHandler('type', $this->getDirname())->get($this->get('type_id'));
		}
	}
	
	/**
	 * getTargetGroupId
	 * 
	 * @param	string	$order
	 * 
	 * @return	void
	**/
	public function getTargetGroupId()
	{
		$result = null;
		$this->loadType();
		XCube_DelegateUtils::call('Legacy_Workflow.GetTargetGroupId', new XCube_Ref($result), $this->get('type_id'),$this->mType->get('module'), $this->get('target_id'));
		return $result;
	}

	/**
	 * getShowStatus
	 * 
	 * @param	void
	 * 
	 * @return	string
	**/
	public function getShowStatus()
	{
		switch($this->get('status')){
			case Lenum_WorkflowStatus::DELETED:
				return _MD_XLEPROGRESS_LANG_STATUS_DELETED;
				break;
			case Lenum_WorkflowStatus::REJECTED:
				return _MD_XLEPROGRESS_LANG_STATUS_REJECTED;
				break;
			case Lenum_WorkflowStatus::PROGRESS:
				return _MD_XLEPROGRESS_LANG_STATUS_PROGRESS;
				break;
			case Lenum_WorkflowStatus::FINISHED:
				return _MD_XLEPROGRESS_LANG_STATUS_FINISHED;
				break;
		}
	}
}

/**
 * Xleprogress_ItemHandler
**/
class Xleprogress_ItemHandler extends XoopsObjectGenericHandler
{
	public /*** string ***/ $mTable = '{dirname}_item';

	public /*** string ***/ $mPrimary = 'item_id';

	public /*** string ***/ $mClass = 'Xleprogress_ItemObject';

	/**
	 * __construct
	 * 
	 * @param	XoopsDatabase  &$db
	 * @param	string	$dirname
	 * 
	 * @return	void
	**/
	public function __construct(/*** XoopsDatabase ***/ &$db,/*** string ***/ $dirname)
	{
		$this->mTable = strtr($this->mTable, array('{dirname}' => $dirname));
		parent::XoopsObjectGenericHandler($db);
	}

	/**
	 * delete
	 * 
	 * @param	Xleprogress_ItemObject  &$obj
	 * 
	 * @return	bool
	**/
	public function delete(/*** Xleprogress_ItemObject ***/ $obj)
	{
		$handler = Legacy_Utils::getModuleHandler('history', $this->getDirname());
		$handler->deleteAll(new Criteria('item_id', $obj->get('item_id')));
		unset($handler);
	
		return parent::delete($obj);
	}

	/**
	 * proceedStep
	 * 
	 * @param	Xleprogress_ItemObject	$obj
	 * 
	 * @return	bool
	**/
	public function proceedStep(/*** Xleprogress_ItemObject ***/ $obj, $comment)
	{
		$approval = Legacy_Utils::getModuleHandler('approval', $obj->getDirname())->getNextApproval($obj->get('type_id'),  $obj->get('step'));
		if(is_object($approval)){
			$obj->set('step', $approval->get('step'));
		}
		else{
			$obj->set('status', Lenum_WorkflowStatus::FINISHED);
		}
		if($this->insert($obj)){
			$obj->loadType();
			$result = array();
			XCube_DelegateUtils::call('Legacy_Workflow.UpdateStatus', new XCube_Ref($result), $obj->get('type_id'), $obj->mType->get('module'), $obj->get('target_id'), $obj->get('status'), $comment);
			if($result[0]==true){
				return true;
			}
			else{
				$obj->set('status', Lenum_WorkflowStatus::PROGRESS);
				return $result[1];
			}
		}
		return false;
	}

	/**
	 * revertStep
	 * 
	 * @param	Xleprogress_ItemObject	$obj
	 * 
	 * @return	void
	**/
	public function revertStep(/*** Xleprogress_ItemObject ***/ $obj, $comment)
	{
		/*$approval = Legacy_Utils::getModuleHandler('approval', $obj->getDirname())->getPreviousApproval($obj->get('type_id'), $obj->get('step'));
		if (is_object($approval)) {
			$obj->set('step', $approval->get('step'));
		} else {*/
			$obj->set('status', Lenum_WorkflowStatus::REJECTED);
		//}
		if($this->insert($obj)){
			$result = array();
			XCube_DelegateUtils::call('Legacy_Workflow.UpdateStatus', new XCube_Ref($result), $obj->get('type_id'),$obj->mType->get('module'), $obj->get('target_id'), $obj->get('status'), $comment);
			if($result[0]==true){
				return true;
			}
			else{
				return $result[1];
			}
		}
		return false;
	}
	
	/**
	 * getUsers
	 * 
	 * @param	int	$groupid
	 * 
	 * @return	Xleprogress_ItemObject
	**/
	public function getByTargetId($type_id,$target_id)
	{
		$cri = new CriteriaCompo();
		$cri->add(new Criteria('type_id',$type_id,'='));
		$cri->add(new Criteria('target_id',$target_id,'='));
		$objs = $this->getObjects($cri);		
		return $objs[0];
	}
	/**
	 * getUsers
	 * 
	 * @param	int	$uid
	 * 
	 * @return	Xleprogress_ItemObject[]
	**/
	public function getMyTaskList($uid) {
		global $xoopsDB;
		$itemObjs = array();

		$adminGroups = array();
        $result = Legacy_Utils::getModuleHandler('approval', $this->getDirname())->getApprovalResult($uid, $adminGroups);
        if ($result!= false) {
	        while ($approval = $xoopsDB->fetchArray($result)) {
	            $cri = new CriteriaCompo();
	            $cri->add(new Criteria('b.deletetime', 0));
	            $cri->add(new Criteria('b.type_id', $approval['type_id']));
	            $cri->add(new Criteria('b.step', $approval['step']));
	            $cri->add(new Criteria('b.status', Lenum_WorkflowStatus::FINISHED, '<>'));
	            $cri->add(new Criteria('b.status', Lenum_WorkflowStatus::REJECTED, '<>'));
	            $objs = $this->getJoinObjects($cri);
	            if ($approval['groupid'] == Xoonips_Enum::XLEPROGRESS_GROUP) {
		            foreach ($objs as $obj) {
		            	//$obj->loadType();
		            	$targetGroup = $obj->getTargetGroupId();
		            	if (in_array($targetGroup,$adminGroups)) {
		            		$itemObjs[] = $obj;
		            	}
		            }
	            } else {
	            	$itemObjs = array_merge($itemObjs, $objs);
	            }
	        }
        }
        return $itemObjs;
	}

	public function getJoinObjects($criteria = null, $limit = null, $start = null, $id_as_key = false) {
		$typeHandler = Legacy_Utils::getModuleHandler('type', $this->getDirname());
		$typeTable = $typeHandler->mTable;
        $itemTable = $this->mTable;
        $sql = "SELECT a.dirname,a.dataname,a.module,b.* FROM $typeTable a,$itemTable b";

       	if($criteria !== null && is_a($criteria, 'CriteriaElement')) {
       		$sql .= " WHERE a.type_id=b.type_id";

       		$where = $this->_makeCriteria4sql($criteria);
			if (trim($where)) {
				$sql .= " and " . $where;
			}
			
			$sorts = array();
			foreach ($criteria->getSorts() as $sort) {
				$sorts[] = '`' . $sort['sort'] . '` ' . $sort['order']; 
			}
			if ($criteria->getSort() != '') {
				$sql .= " ORDER BY " . implode(',', $sorts);
			}
			
			if ($limit === null) {
				$limit = $criteria->getLimit();
			}
			
			if ($start === null) {
				$start = $criteria->getStart();
			}
		}
		else {
			if ($limit === null) {
				$limit = 0;
			}
			
			if ($start === null) {
				$start = 0;
			}
		}

		$result = $this->db->query($sql, $limit, $start);

		$ret = array();
		if (!$result) {
			return $ret;
		}

		while($row = $this->db->fetchArray($result)) {
			$obj =new $this->mClass();
			$obj->mDirname = $this->getDirname();
			$obj->assignVars($row);
			$obj->unsetNew();
			
			$typeObj = new $typeHandler->mClass();
			$typeObj->mDirname = $this->getDirname();
			$typeObj->assignVars($row);
			$typeObj->unsetNew();
			$obj->mType = $typeObj;

			if ($id_as_key)	{
				$ret[$obj->get($this->mPrimary)] =& $obj;
			}
			else {
				$ret[]=&$obj;
			}
		
			unset($obj);
		}
		return $ret;
	}
}
?>
