/**
 * 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.polls.uad.anonymizer;

import com.liferay.asset.kernel.model.AssetEntry;
import com.liferay.asset.kernel.service.AssetEntryLocalService;
import com.liferay.polls.model.PollsVote;
import com.liferay.polls.service.PollsVoteLocalService;
import com.liferay.polls.uad.constants.PollsUADConstants;
import com.liferay.portal.kernel.dao.orm.ActionableDynamicQuery;
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(service = UADAnonymizer.class)
public class PollsVoteUADAnonymizer extends BasePollsVoteUADAnonymizer {

	@Override
	public void autoAnonymize(
			PollsVote pollsVote, long userId, User anonymousUser)
		throws PortalException {

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

			autoAnonymizeAssetEntry(pollsVote, anonymousUser);
		}

		pollsVoteLocalService.updatePollsVote(pollsVote);
	}

	@Override
	public void delete(PollsVote pollsVote) throws PortalException {
		pollsVoteLocalService.deletePollsVote(pollsVote);
	}

	@Override
	public Class<PollsVote> getTypeClass() {
		return PollsVote.class;
	}

	protected void autoAnonymizeAssetEntry(
		PollsVote pollsVote, User anonymousUser) {

		AssetEntry assetEntry = fetchAssetEntry(pollsVote);

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

			assetEntryLocalService.updateAssetEntry(assetEntry);
		}
	}

	@Override
	protected ActionableDynamicQuery doGetActionableDynamicQuery() {
		return pollsVoteLocalService.getActionableDynamicQuery();
	}

	@Override
	protected String[] doGetUserIdFieldNames() {
		return PollsUADConstants.USER_ID_FIELD_NAMES_POLLS_VOTE;
	}

	protected AssetEntry fetchAssetEntry(PollsVote pollsVote) {
		return assetEntryLocalService.fetchEntry(
			PollsVote.class.getName(), pollsVote.getVoteId());
	}

	@Reference
	protected AssetEntryLocalService assetEntryLocalService;

	@Reference
	protected PollsVoteLocalService pollsVoteLocalService;

}