/*-
 * ~~~~~~licensing~~~~~~
 * test-producers
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.platform.core.producer.executor.objectmodel;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import ru.entaxy.platform.base.objects.EntaxyObject;
import ru.entaxy.platform.base.objects.EntaxyObject.FIELDS;


public class FactoredObject extends AbstractFactored {

	private static final Logger log = LoggerFactory.getLogger(FactoredObject.class);
	
	public static String EMBEDDED_FIELD = "##embedded";
	public static final String IGNORE_SECTION = "##ignore";


	public static String IS_EMBEDDED_FIELD = "isEmbedded";
	
	public List<FactoredObject> dependsOn = new ArrayList<>();
	public List<FactoredObject> dependants = new ArrayList<>();
	
	public List<FactoredObjectRef> references = new ArrayList<>();
	
	public List<AbstractFactored> embedded = new ArrayList<>();
	
	protected String objectId = "";
	protected String targetType = "";
	
	protected String outputType = "";
	
	protected boolean isEmbedded = false;
	
	public FactoredObject (ObjectModel objectModel) {
		super(objectModel);
	}
	
	@Override
	public void wrap(JsonObject object, Map<String, Object> context, String path) {
		super.wrap(object, context, path);
		if (object.has(FIELDS.SCOPE)) {
			this.ownScope = object.get(FIELDS.SCOPE).getAsString(); 
			if (!this.ownScope.isEmpty())
				this.scope = this.ownScope;
		}
		if (object.has(FIELDS.OBJECT_ID))
			this.objectId = object.get(FIELDS.OBJECT_ID).getAsString();
		else
			this.setObjectId("TEMP-" + UUID.randomUUID().toString());
		if (object.has(FIELDS.OBJECT_TYPE))
			this.targetType = object.get(FIELDS.OBJECT_TYPE).getAsString();
		
		if (object.has("outputType"))
			this.outputType = object.get("outputType").getAsString(); 

		if (object.has(IS_EMBEDDED_FIELD))
			try{
				this.isEmbedded = object.get(IS_EMBEDDED_FIELD).getAsBoolean();
			} catch (Exception e) {
				
			}
		
		log.debug("\t CURRENT SCOPE :: " + this.scope);
		initContext(context);
		AbstractFactored contextOwner = getContextOwner(context);
		if ((contextOwner != null) && (contextOwner instanceof FactoredObject)) {
			FactoredObject fo = (FactoredObject)contextOwner;
			log.debug("\t IN CONTEXT :: " + fo.factoryId + "[" + fo.jsonPath + "]");
			computeRelativePath(fo.jsonPath);
			if (null == this.ownScope || this.ownScope.isEmpty())
				this.scope = fo.scope;
			fo.dependsOn(this);
			this.definedIn = fo;
			if ("#OWNER#".equals(this.factoryId)) {
				this.factoryId = fo.factoryId;
				this.origin.remove(EntaxyObject.FIELDS.FACTORY_ID);
				this.origin.addProperty(EntaxyObject.FIELDS.FACTORY_ID, this.factoryId);
			}
		}
		log.debug("\t EFFECTIVE SCOPE :: " + this.scope);
		objectModel.addObject(this);
		joinContext(context);
	}
	
	public String getObjectId() {
		return objectId;
	}

	public void embed(AbstractFactored factored) {
		this.embedded.add(factored);
		this.embed(factored.origin);
	}

	protected void embed(JsonElement jsonElement) {
		if (!this.origin.has(EMBEDDED_FIELD))
			this.origin.add(EMBEDDED_FIELD, new JsonArray());
		this.origin.get(EMBEDDED_FIELD).getAsJsonArray().add(jsonElement);
	}
	
	public void dependsOn(FactoredObject fo) {
		this.dependsOn.add(fo);
		fo.dependants.add(this);
	}
	
	@Override
	public void setTraverseMap(Map<String, Object> traverseMap, Map<String, Object> context) {
		super.setTraverseMap(traverseMap, context);
		leaveContext(context);
	}

	public String getObjectType() {
		return targetType;
	}

	public void setObjectType(String targetType) {
		this.targetType = targetType;
		this.origin.remove(FIELDS.OBJECT_TYPE);
		this.origin.addProperty(FIELDS.OBJECT_TYPE, this.getObjectType());
	}

	public void setObjectId(String objectId) {
		this.objectId = objectId;
		this.origin.remove(FIELDS.OBJECT_ID);
		this.origin.addProperty(FIELDS.OBJECT_ID, this.getObjectId());
	}

	public String getOutputType() {
		return outputType;
	}

	public boolean isEmbedded() {
		return isEmbedded;
	}

	public void setEmbedded(boolean isEmbedded) {
		this.isEmbedded = isEmbedded;
		this.origin.remove(IS_EMBEDDED_FIELD);
		this.origin.addProperty(IS_EMBEDDED_FIELD, isEmbedded);
	}
	
	public FactoredObject getOwnerObject() {
		if (this.definedIn != null)
			return this.definedIn;
		if (this.isEmbedded) {
			List<FactoredObjectRef> refs = this.objectModel.refs.stream()
				.filter(r->r.isLink)
				.filter(r->r.targetObject==this)
				.collect(Collectors.toList());
			if (!refs.isEmpty())
				return refs.get(0).definedIn;
		}
		// try to find refs with 'isDefinitionOrigin' set to 'true'
		List<FactoredObjectRef> refs = this.objectModel.refs.stream()
				.filter(r->r.isDefinitionOrigin())
				.filter(r->r.targetObject==this)
				.collect(Collectors.toList());
			if (!refs.isEmpty())
				return refs.get(0).definedIn;
		
		return null;
	}
	
}
