<?php

require_once XOOPS_TRUST_PATH . '/libs/xoonips/class/core/WorkflowBase.class.php';
require_once XOOPS_TRUST_PATH . '/libs/xoonips/class/core/BeanFactory.class.php';
require_once XOOPS_TRUST_PATH . '/libs/xoonips/class/core/WorkflowFactory.class.php';
require_once dirname(dirname(__FILE__)) . '/core/User.class.php';

class User_WorkflowGroupLeave extends Xoonips_WorkflowBase {

	public function doCertify($linkId, &$result, $comment) {
		$result[0] = false;
		$groupsUsersLinkBean = null;
		list($gid, $uid) = $this->getTargetGroupId($linkId, $groupsUsersLinkBean);
		if ($uid == 0 || !$groupsUsersLinkBean->delete($gid, $uid)) {
			return false;
		}
		$result[0] = true;
		$group_handler =& xoops_gethandler('group');
		$xoopsGroup = $group_handler->get($gid);
		//event log
		$user = User_User::getInstance();
		$user->doGroupLeaved($gid, $uid, $xoopsGroup, false, $comment);
	}

	public function doProgress($linkId, &$result, $comment) {
		$result[0] = false;
		$groupsUsersLinkBean = null;
		list($gid, $uid) = $this->getTargetGroupId($linkId, $groupsUsersLinkBean);
		if ($uid == 0) {
			return false;
		}
		//send to group admins and certifyUsers
		$sendToUsers[$uid] = $uid;
		foreach ($groupsUsersLinkBean->getAdminUserIds($gid) as $id) {
			$sendToUsers[$id] = $id;
		}
		XCube_DelegateUtils::call('Legacy_Workflow.GetCurrentCertifyUsers', Xoonips_Enum::certifyGroupLeave(), $linkId, new XCube_Ref($sendToUsers));
		$this->notification->groupLeaveRequest($gid, $uid, $sendToUsers);
		$result[0] = true;
	}

	public function doRefuse($linkId, &$result, $comment) {
		$result[0] = false;
		$groupsUsersLinkBean = null;
		list($gid, $uid) = $this->getTargetGroupId($linkId, $groupsUsersLinkBean);
		if ($uid == 0 || !$groupsUsersLinkBean->certify($gid, $uid)) {
			return false;
		}
		$result[0] = true;
		$group_handler =& xoops_gethandler('group');
		$xoopsGroup = $group_handler->get($gid);
		//event log
		XCube_DelegateUtils::call('Module.User.Event.Group.Member.LeaveReject', new XoopsUser($uid), $xoopsGroup);
		//send to group admins and certifyUsers
		$sendToUsers[$uid] = $uid;
		foreach ($groupsUsersLinkBean->getAdminUserIds($gid) as $id) {
			$sendToUsers[$id] = $id; 
		}
		XCube_DelegateUtils::call('Legacy_Workflow.GetAllCertifyUsers', Xoonips_Enum::certifyGroupLeave(), new XCube_Ref($sendToUsers));
		$this->notification->groupLeaveRejected($gid, $uid, $sendToUsers, $comment);
	}
	
	public function getDetailView($linkId) {
		$workflow = Xoonips_WorkflowFactory::getWorkflow('WorkflowGroupJoin', $this->dirname, $this->trustDirname);
		return $workflow->getDetailView($linkId);
	}
	
	public function getTargetGroupId($linkId, &$groupsUsersLinkBean) {
		$workflow = Xoonips_WorkflowFactory::getWorkflow('WorkflowGroupJoin', $this->dirname, $this->trustDirname);
		return $workflow->getTargetGroupId($linkId, $groupsUsersLinkBean);
	}
}

