/*-
 * ~~~~~~licensing~~~~~~
 * test-producers
 * ==========
 * Copyright (C) 2020 - 2022 EmDev LLC
 * ==========
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.platform.core.producer.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import ru.entaxy.esb.platform.runtime.base.connecting.generator.Generated;
import ru.entaxy.platform.base.objects.EntaxyObject.FIELDS;
import ru.entaxy.platform.base.objects.factory.EntaxyFactoryException;
import ru.entaxy.platform.core.producer.api.EntaxyWrappedFactory;
import ru.entaxy.platform.core.producer.wrapper.AbstractFactoryWrapper;
import ru.entaxy.platform.core.producer.wrapper.AbstractFactoryWrapper.GenerationProcessor;

public class CommonObjectProducer extends DefaultProducer implements GenerationProcessor {
	
	protected final Map<String, String> defaultFieldsPublished = new HashMap<>() {
		private static final long serialVersionUID = 1L;

	{
		put(FIELDS.OBJECT_ID, FIELDS.OBJECT_ID);
	}}; 
	
	protected Map<String, String> getFieldsToPublish(String outputType, String scope, String objectType, String objectId){
		return defaultFieldsPublished;
	}
	
	@Override
	protected void addFields(AbstractFactoryWrapper factoryWrapper) {
		super.addFields(factoryWrapper);
		factoryWrapper.addField(
				(new FieldInfoImpl())
				.name(FIELDS.OBJECT_ID)
				.type("String")
				.required(true)
				.immutable(true)
					);
	}

	@Override
	public void postGenerate(EntaxyWrappedFactory wrappedFactory, String outputType, String scope, String objectType, Map<String, Object> parameters,
			Generated generated) throws EntaxyFactoryException {
		
		String objectId = parameters.getOrDefault(FIELDS.OBJECT_ID, "").toString();
		
		Map<String, String> publishedFields = getFieldsToPublish(outputType, scope, objectType, objectId);
		
		Map<String, Object> dataToPublish = new HashMap<>();
		for (Entry<String, String> entry: publishedFields.entrySet())
			dataToPublish.put(entry.getKey(), generated.getProperties().get(entry.getValue()));
		
		generated.getProperties().put(FIELDS.FIELDS_TO_PUBLISH, new HashMap<String, Map<String, Object>>() {{
			put(objectId, dataToPublish);
		}});
	}
	
}
