/**
 * 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.PollsQuestion;
import com.liferay.polls.service.PollsQuestionLocalService;
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 PollsQuestionUADAnonymizer extends BasePollsQuestionUADAnonymizer {

	@Override
	public void autoAnonymize(
			PollsQuestion pollsQuestion, long userId, User anonymousUser)
		throws PortalException {

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

			autoAnonymizeAssetEntry(pollsQuestion, anonymousUser);
		}

		pollsQuestionLocalService.updatePollsQuestion(pollsQuestion);
	}

	@Override
	public void delete(PollsQuestion pollsQuestion) throws PortalException {
		pollsQuestionLocalService.deleteQuestion(pollsQuestion);
	}

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

	protected void autoAnonymizeAssetEntry(
		PollsQuestion pollsQuestion, User anonymousUser) {

		AssetEntry assetEntry = fetchAssetEntry(pollsQuestion);

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

			assetEntryLocalService.updateAssetEntry(assetEntry);
		}
	}

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

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

	protected AssetEntry fetchAssetEntry(PollsQuestion pollsQuestion) {
		return assetEntryLocalService.fetchEntry(
			PollsQuestion.class.getName(), pollsQuestion.getQuestionId());
	}

	@Reference
	protected AssetEntryLocalService assetEntryLocalService;

	@Reference
	protected PollsQuestionLocalService pollsQuestionLocalService;

}