/**
 * 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.ResourceBlock;
import com.liferay.portal.model.ResourceConstants;
import com.liferay.portal.model.impl.ResourceBlockModelImpl;

/**
 * @author Preston Crary
 */
public class ResourceBlockModelListener
	extends BaseModelListener<ResourceBlock> {

	@Override
	public void onAfterCreate(ResourceBlock resourceBlock) {
		_clearCache(resourceBlock);
	}

	@Override
	public void onAfterRemove(ResourceBlock resourceBlock) {
		_clearCache(resourceBlock);
	}

	@Override
	public void onAfterUpdate(ResourceBlock resourceBlock) {
		_clearCache(resourceBlock);
	}

	@Override
	public void onBeforeUpdate(ResourceBlock resourceBlock) {
		ResourceBlockModelImpl resourceBlockModelImpl =
			(ResourceBlockModelImpl)resourceBlock;

		long columnBitmask = resourceBlockModelImpl.getColumnBitmask();

		if ((columnBitmask & _CLEAR_ON_BEFORE_BITMASK) != 0) {
			PermissionCacheUtil.clearResourceBlockCache(
				resourceBlockModelImpl.getOriginalCompanyId(),
				resourceBlockModelImpl.getOriginalGroupId(),
				resourceBlockModelImpl.getOriginalName());
		}
	}

	private void _clearCache(ResourceBlock resourceBlock) {
		if (resourceBlock != null) {
			PermissionCacheUtil.clearResourceBlockCache(
				resourceBlock.getCompanyId(), resourceBlock.getGroupId(),
				resourceBlock.getName());

			PermissionCacheUtil.clearResourcePermissionCache(
				ResourceConstants.SCOPE_INDIVIDUAL, resourceBlock.getName(),
				String.valueOf(resourceBlock.getPrimaryKey()));
		}
	}

	private static final long _CLEAR_ON_BEFORE_BITMASK =
		ResourceBlockModelImpl.COMPANYID_COLUMN_BITMASK |
			ResourceBlockModelImpl.GROUPID_COLUMN_BITMASK |
				ResourceBlockModelImpl.NAME_COLUMN_BITMASK;

}