/**
 * Copyright (c) 2000-2017 Liferay, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of the Liferay Enterprise
 * pSubscription License ("License"). You may not use this file except in
 * compliance with the License. You can obtain a copy of the License by
 * contacting Liferay, Inc. See the License for the specific language governing
 * permissions and limitations under the License, including but not limited to
 * distribution rights of the Software.
 *
 *
 *
 */

package com.liferay.portal.security.permission;

import com.liferay.portal.model.BaseModelListener;
import com.liferay.portal.model.ResourcePermission;
import com.liferay.portal.model.impl.ResourcePermissionModelImpl;

/**
 * @author Preston Crary
 */
public class ResourcePermissionModelListener
	extends BaseModelListener<ResourcePermission> {

	@Override
	public void onAfterCreate(ResourcePermission resourcePermission) {
		_clearCache(resourcePermission);
	}

	@Override
	public void onAfterRemove(ResourcePermission resourcePermission) {
		_clearCache(resourcePermission);
	}

	@Override
	public void onAfterUpdate(ResourcePermission resourcePermission) {
		_clearCache(resourcePermission);
	}

	@Override
	public void onBeforeUpdate(ResourcePermission resourcePermission) {
		ResourcePermissionModelImpl resourcePermissionModelImpl =
			(ResourcePermissionModelImpl)resourcePermission;

		long columnBitmask = resourcePermissionModelImpl.getColumnBitmask();

		if ((columnBitmask & _CLEAR_ON_BEFORE_BITMASK) != 0) {
			PermissionCacheUtil.clearResourcePermissionCache(
				resourcePermissionModelImpl.getOriginalScope(),
				resourcePermissionModelImpl.getOriginalName(),
				resourcePermissionModelImpl.getOriginalPrimKey());
		}
	}

	private void _clearCache(ResourcePermission resourcePermission) {
		if (resourcePermission != null) {
			PermissionCacheUtil.clearResourcePermissionCache(
				resourcePermission.getScope(), resourcePermission.getName(),
				resourcePermission.getPrimKey());
		}
	}

	private static final long _CLEAR_ON_BEFORE_BITMASK =
		ResourcePermissionModelImpl.NAME_COLUMN_BITMASK |
			ResourcePermissionModelImpl.PRIMKEY_COLUMN_BITMASK;

}