/**
 * 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.PollsChoice;
import com.liferay.polls.service.PollsChoiceLocalService;
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 PollsChoiceUADAnonymizer extends BasePollsChoiceUADAnonymizer {

	@Override
	public void autoAnonymize(
			PollsChoice pollsChoice, long userId, User anonymousUser)
		throws PortalException {

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

			autoAnonymizeAssetEntry(pollsChoice, anonymousUser);
		}

		pollsChoiceLocalService.updatePollsChoice(pollsChoice);
	}

	@Override
	public void delete(PollsChoice pollsChoice) throws PortalException {
		pollsChoiceLocalService.deletePollsChoice(pollsChoice);
	}

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

	protected void autoAnonymizeAssetEntry(
		PollsChoice pollsChoice, User anonymousUser) {

		AssetEntry assetEntry = fetchAssetEntry(pollsChoice);

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

			assetEntryLocalService.updateAssetEntry(assetEntry);
		}
	}

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

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

	protected AssetEntry fetchAssetEntry(PollsChoice pollsChoice) {
		return assetEntryLocalService.fetchEntry(
			PollsChoice.class.getName(), pollsChoice.getChoiceId());
	}

	@Reference
	protected AssetEntryLocalService assetEntryLocalService;

	@Reference
	protected PollsChoiceLocalService pollsChoiceLocalService;

}