/**
 * 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.journal.internal.exportimport.content.processor;

import com.liferay.document.library.kernel.model.DLFileEntry;
import com.liferay.document.library.kernel.service.DLAppLocalService;
import com.liferay.dynamic.data.mapping.model.DDMFormFieldType;
import com.liferay.dynamic.data.mapping.model.Value;
import com.liferay.dynamic.data.mapping.storage.DDMFormFieldValue;
import com.liferay.dynamic.data.mapping.util.DDMFormFieldValueTransformer;
import com.liferay.exportimport.kernel.lar.PortletDataContext;
import com.liferay.journal.model.JournalArticle;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.json.JSONException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.json.JSONUtil;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.model.StagedModel;
import com.liferay.portal.kernel.repository.model.FileEntry;
import com.liferay.portal.kernel.util.Validator;

import java.util.Locale;
import java.util.Map;

/**
 * @author Pavel Savinov
 */
public class ImageImportDDMFormFieldValueTransformer
	implements DDMFormFieldValueTransformer {

	public ImageImportDDMFormFieldValueTransformer(
		DLAppLocalService dlAppLocalService,
		PortletDataContext portletDataContext, StagedModel stagedModel) {

		_dlAppLocalService = dlAppLocalService;
		_portletDataContext = portletDataContext;
		_stagedModel = stagedModel;
	}

	@Override
	public String getFieldType() {
		return DDMFormFieldType.IMAGE;
	}

	@Override
	public void transform(DDMFormFieldValue ddmFormFieldValue)
		throws PortalException {

		Value value = ddmFormFieldValue.getValue();

		for (Locale locale : value.getAvailableLocales()) {
			JSONObject jsonObject = null;

			try {
				jsonObject = JSONFactoryUtil.createJSONObject(
					value.getString(locale));
			}
			catch (JSONException jsonException) {
				if (_log.isDebugEnabled()) {
					_log.debug("Unable to parse JSON", jsonException);
				}

				continue;
			}

			FileEntry importedFileEntry = fetchImportedFileEntry(
				_portletDataContext, jsonObject.getLong("fileEntryId"),
				jsonObject.getString("uuid"));

			if (importedFileEntry == null) {
				continue;
			}

			value.addString(
				locale,
				toJSON(
					importedFileEntry, jsonObject.getString("type"),
					jsonObject.getString("alt")));
		}
	}

	protected FileEntry fetchImportedFileEntry(
			PortletDataContext portletDataContext, long oldClassPK, String uuid)
		throws PortalException {

		try {
			Map<Long, Long> fileEntryPKs =
				(Map<Long, Long>)portletDataContext.getNewPrimaryKeysMap(
					DLFileEntry.class);

			Long classPK = fileEntryPKs.get(oldClassPK);

			if (classPK == null) {
				if (Validator.isNotNull(uuid)) {
					return _dlAppLocalService.getFileEntryByUuidAndGroupId(
						uuid, portletDataContext.getScopeGroupId());
				}

				return null;
			}

			return _dlAppLocalService.getFileEntry(classPK);
		}
		catch (PortalException portalException) {
			if (_log.isWarnEnabled()) {
				_log.warn("Unable to find file entry", portalException);
			}
		}

		return null;
	}

	protected String toJSON(FileEntry fileEntry, String type, String alt) {
		JournalArticle article = (JournalArticle)_stagedModel;

		JSONObject jsonObject = JSONUtil.put(
			"alt", alt
		).put(
			"fileEntryId", fileEntry.getFileEntryId()
		).put(
			"groupId", fileEntry.getGroupId()
		).put(
			"name", fileEntry.getFileName()
		).put(
			"resourcePrimKey", article.getResourcePrimKey()
		).put(
			"title", fileEntry.getTitle()
		).put(
			"type", type
		).put(
			"uuid", fileEntry.getUuid()
		);

		return jsonObject.toString();
	}

	private static final Log _log = LogFactoryUtil.getLog(
		ImageImportDDMFormFieldValueTransformer.class);

	private final DLAppLocalService _dlAppLocalService;
	private final PortletDataContext _portletDataContext;
	private final StagedModel _stagedModel;

}