/**
 * 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.friendly.url.internal.exportimport.data.handler;

import com.liferay.exportimport.data.handler.base.BaseStagedModelDataHandler;
import com.liferay.exportimport.kernel.lar.ExportImportPathUtil;
import com.liferay.exportimport.kernel.lar.PortletDataContext;
import com.liferay.exportimport.kernel.lar.StagedModelDataHandler;
import com.liferay.exportimport.staged.model.repository.StagedModelRepository;
import com.liferay.friendly.url.model.FriendlyURLEntry;
import com.liferay.friendly.url.service.FriendlyURLEntryLocalService;
import com.liferay.portal.kernel.service.ClassNameLocalService;
import com.liferay.portal.kernel.util.FriendlyURLNormalizerUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.MapUtil;
import com.liferay.portal.kernel.xml.Element;

import java.util.List;
import java.util.Map;

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

/**
 * @author Adolfo Pérez
 */
@Component(immediate = true, service = StagedModelDataHandler.class)
public class FriendlyURLEntryStagedModelDataHandler
	extends BaseStagedModelDataHandler<FriendlyURLEntry> {

	public static final String[] CLASS_NAMES = {
		FriendlyURLEntry.class.getName()
	};

	@Override
	public FriendlyURLEntry fetchStagedModelByUuidAndGroupId(
		String uuid, long groupId) {

		return _stagedModelRepository.fetchStagedModelByUuidAndGroupId(
			uuid, groupId);
	}

	@Override
	public List<FriendlyURLEntry> fetchStagedModelsByUuidAndCompanyId(
		String uuid, long companyId) {

		return _stagedModelRepository.fetchStagedModelsByUuidAndCompanyId(
			uuid, companyId);
	}

	@Override
	public String[] getClassNames() {
		return CLASS_NAMES;
	}

	@Override
	protected void doExportStagedModel(
			PortletDataContext portletDataContext,
			FriendlyURLEntry friendlyURLEntry)
		throws Exception {

		Element friendlyURLEntryElement =
			portletDataContext.getExportDataElement(friendlyURLEntry);

		friendlyURLEntryElement.addAttribute(
			"resource-class-name", friendlyURLEntry.getClassName());

		String modelPath = ExportImportPathUtil.getModelPath(
			friendlyURLEntry, friendlyURLEntry.getUuid());

		portletDataContext.addZipEntry(
			modelPath, friendlyURLEntry.getUrlTitleMapAsXML());

		if (friendlyURLEntry.isMain()) {
			friendlyURLEntryElement.addAttribute(
				"mainEntry", Boolean.TRUE.toString());
		}

		portletDataContext.addClassedModel(
			friendlyURLEntryElement,
			ExportImportPathUtil.getModelPath(friendlyURLEntry),
			friendlyURLEntry);
	}

	@Override
	protected void doImportStagedModel(
			PortletDataContext portletDataContext,
			FriendlyURLEntry friendlyURLEntry)
		throws Exception {

		Element friendlyURLEntryElement =
			portletDataContext.getImportDataStagedModelElement(
				friendlyURLEntry);

		String className = friendlyURLEntryElement.attributeValue(
			"resource-class-name");

		long classNameId = _classNameLocalService.getClassNameId(className);

		Map<Long, Long> newPrimaryKeysMap =
			(Map<Long, Long>)portletDataContext.getNewPrimaryKeysMap(className);

		String normalizedUrlTitle = FriendlyURLNormalizerUtil.normalize(
			friendlyURLEntry.getUrlTitle());

		FriendlyURLEntry existingFriendlyURLEntry =
			_friendlyURLEntryLocalService.fetchFriendlyURLEntry(
				portletDataContext.getScopeGroupId(),
				friendlyURLEntry.getClassNameId(), normalizedUrlTitle);

		if ((existingFriendlyURLEntry == null) ||
			!portletDataContext.isDataStrategyMirror()) {

			FriendlyURLEntry importedFriendlyURLEntry =
				(FriendlyURLEntry)friendlyURLEntry.clone();

			importedFriendlyURLEntry.setGroupId(
				portletDataContext.getScopeGroupId());
			importedFriendlyURLEntry.setCompanyId(
				portletDataContext.getCompanyId());
			importedFriendlyURLEntry.setClassNameId(classNameId);

			long classPK = MapUtil.getLong(
				newPrimaryKeysMap, friendlyURLEntry.getClassPK(),
				friendlyURLEntry.getClassPK());

			importedFriendlyURLEntry.setClassPK(classPK);

			importedFriendlyURLEntry.setDefaultLanguageId(
				friendlyURLEntry.getDefaultLanguageId());

			_stagedModelRepository.addStagedModel(
				portletDataContext, importedFriendlyURLEntry);
		}
		else {
			_stagedModelRepository.updateStagedModel(
				portletDataContext, existingFriendlyURLEntry);

			boolean mainEntry = GetterUtil.getBoolean(
				friendlyURLEntryElement.attributeValue("mainEntry"));

			if (mainEntry) {
				_friendlyURLEntryLocalService.setMainFriendlyURLEntry(
					existingFriendlyURLEntry);
			}
		}
	}

	@Override
	protected StagedModelRepository<FriendlyURLEntry>
		getStagedModelRepository() {

		return _stagedModelRepository;
	}

	@Reference
	private ClassNameLocalService _classNameLocalService;

	@Reference
	private FriendlyURLEntryLocalService _friendlyURLEntryLocalService;

	@Reference(
		target = "(model.class.name=com.liferay.friendly.url.model.FriendlyURLEntry)"
	)
	private StagedModelRepository<FriendlyURLEntry> _stagedModelRepository;

}