/**
 * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of the Liferay Enterprise
 * Subscription 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.blogs.uad.anonymizer;

import com.liferay.asset.kernel.model.AssetEntry;
import com.liferay.asset.kernel.service.AssetEntryLocalService;
import com.liferay.blogs.kernel.model.BlogsEntry;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.model.User;
import com.liferay.user.associated.data.anonymizer.UADAnonymizer;

import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;

/**
 * @author Brian Wing Shun Chan
 */
@Component(immediate = true, service = UADAnonymizer.class)
public class BlogsEntryUADAnonymizer extends BaseBlogsEntryUADAnonymizer {

	@Override
	public void autoAnonymize(
			BlogsEntry blogsEntry, long userId, User anonymousUser)
		throws PortalException {

		if (blogsEntry.getUserId() == userId) {
			blogsEntry.setUserId(anonymousUser.getUserId());
			blogsEntry.setUserName(anonymousUser.getFullName());

			autoAnonymizeAssetEntry(blogsEntry, anonymousUser);
		}

		if (blogsEntry.getStatusByUserId() == userId) {
			blogsEntry.setStatusByUserId(anonymousUser.getUserId());
			blogsEntry.setStatusByUserName(anonymousUser.getFullName());
		}

		blogsEntryLocalService.updateBlogsEntry(blogsEntry);
	}

	protected void autoAnonymizeAssetEntry(
		BlogsEntry blogsEntry, User anonymousUser) {

		AssetEntry assetEntry = fetchAssetEntry(blogsEntry);

		if (assetEntry != null) {
			assetEntry.setUserId(anonymousUser.getUserId());
			assetEntry.setUserName(anonymousUser.getFullName());

			assetEntryLocalService.updateAssetEntry(assetEntry);
		}
	}

	protected AssetEntry fetchAssetEntry(BlogsEntry blogsEntry) {
		return assetEntryLocalService.fetchEntry(
			BlogsEntry.class.getName(), blogsEntry.getEntryId());
	}

	@Reference
	protected AssetEntryLocalService assetEntryLocalService;

}