/*-
 * ~~~~~~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.base.objects.factory.configuration;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;

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

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

import ru.entaxy.esb.platform.runtime.base.connecting.generator.factory.GeneratorFactory;
import ru.entaxy.platform.base.objects.factory.EntaxyFactory;
import ru.entaxy.platform.base.objects.factory.EntaxyFactory.FieldInfo;
import ru.entaxy.platform.base.objects.factory.EntaxyFactory.SCOPE;

public class OutputElement implements EntaxyFactory.OutputInfo {
	
	private static final Logger log = LoggerFactory.getLogger(OutputElement.class);
	
	protected String type;
	protected String generator = GeneratorFactory.DEFAULT_GENERATOR;
	protected boolean isDefault = false;
	
	protected List<String> scopes = Arrays.asList(new String[] {EntaxyFactory.SCOPE.PUBLIC.name()});
	protected Set<SCOPE> supportedScopes = new HashSet<>( Arrays.asList(new SCOPE[] {EntaxyFactory.SCOPE.PUBLIC}) );
	
	protected Map<String, Object> config = new HashMap<>();

	protected JsonObject origin;
	
	protected FieldsElement fields = null;
	
	protected Map<String, FieldElement> commonFields = new LinkedHashMap<>(); 
	
	protected Map<String, FieldElement> effectiveFields = new LinkedHashMap<>();
	
	protected boolean isEffectiveCalculated = false;
	
	public static OutputElement fromJson(JsonObject jsonObject) {
		Gson gson = new Gson();
		
		OutputElement result = gson.fromJson(jsonObject, OutputElement.class);
		result.setOrigin(jsonObject);
		result.updateFromOrigin();
		
		return result;
	}

	public static OutputElement fromJson(String type, JsonObject jsonObject) {
		OutputElement result = OutputElement.fromJson(jsonObject);
		result.setType(type);
		return result;
	}
	
	public OutputElement() {
		super();
	}
	
	public void updateFromOrigin() {
		if (origin.has(EntaxyFactory.CONFIGURATION.OUTPUTS.ATTRIBUTES.FIELDS)) {
			JsonElement fieldsElement = origin.get(EntaxyFactory.CONFIGURATION.OUTPUTS.ATTRIBUTES.FIELDS);
			this.fields = (new FieldsElement()).fromJson(fieldsElement); 
		}
		if (origin.has(EntaxyFactory.CONFIGURATION.OUTPUTS.ATTRIBUTES.SCOPES)) {
			JsonElement scopesElement = origin.get(EntaxyFactory.CONFIGURATION.OUTPUTS.ATTRIBUTES.SCOPES);
			if (scopesElement.isJsonArray()) {
				JsonArray ja = scopesElement.getAsJsonArray();
				List<String> scopes = new ArrayList<>();
				for (int i=0; i<ja.size(); i++)
					scopes.add(ja.get(i).getAsString());
				setScopes(scopes);
			}
		}
	}
	
	protected void calculateEffective() {
		
		this.effectiveFields.clear();
		
		log.debug("-> " + getType() + " calculateEffective :: " + this.commonFields.size());

		Map<String, FieldElement> ownedFields;
		
		if (fields == null) {
			// get all common fields
			log.debug("-> " + getType() + " taking all common fields");
			ownedFields = Collections.emptyMap();
			if (commonFields != null)
				for (Entry<String, FieldElement> entry: commonFields.entrySet()) {
					this.effectiveFields.put(entry.getKey(), entry.getValue());
				}
			
		} else {
			// use only locally mentioned fields
			// except common fields with "addToOutput" set to current output type or "*"
			
			ownedFields = fields.getFieldsMap();
			log.debug("->" + getType() + " ownedFields: " + fields.getFieldsMap().size());
			
			if (commonFields != null)
				for (Entry<String, FieldElement> entry: commonFields.entrySet()) {
					if (ownedFields.containsKey(entry.getKey())) {
						FieldElement fe = FieldElement.merge(entry.getValue(), ownedFields.get(entry.getKey()));
						fe.setName(entry.getKey());
						this.effectiveFields.put(entry.getKey(), fe);
					} else {
						if (entry.getValue().getJsonOrigin().has(EntaxyFactory.CONFIGURATION.FIELDS.ATTRIBUTES.ADD_TO_OUTPUT)) {
							String value = entry.getValue().getJsonOrigin()
									.get(EntaxyFactory.CONFIGURATION.FIELDS.ATTRIBUTES.ADD_TO_OUTPUT)
									.getAsString();
							String[] values = value.split(",");
							boolean addField = false;
							for (int i=0; i<values.length; i++)
								if ("*".equals(values[i].trim()) || this.type.equals(values[i].trim())) {
									addField = true;
									break;
								}
							
							if (addField)
								this.effectiveFields.put(entry.getKey(), entry.getValue());
							
						}
					}
				}
		}
		for (Entry<String, FieldElement> entry: ownedFields.entrySet())
			if (!this.effectiveFields.containsKey(entry.getKey()))
				this.effectiveFields.put(entry.getKey(), entry.getValue());
		
		this.isEffectiveCalculated = true;
	}
	
	@Override
	public String getType() {
		return type;
	}

	@Override
	public String getGenerator() {
		return generator;
	}
	
	@Override
	public List<String> getScopes() {
		return this.supportedScopes.stream().map(s -> s.label).collect(Collectors.toList());
	}
	
	@Override
	public Map<String, Object> getConfig() {
		return config;
	}

	@Override
	public List<FieldInfo> getFields() {
		if (!this.isEffectiveCalculated)
			calculateEffective();
		return this.effectiveFields.values().stream().map(f->(FieldInfo)f).collect(Collectors.toList());
	}
	
	@Override
	public boolean isDefault() {
		return isDefault;
	}

	public void setType(String type) {
		this.type = type;
	}
	public void setGenerator(String generator) {
		this.generator = generator;
	}
	
	public void setScopes(String[] scopes) {
		log.debug("\n\tsetScopes(String[] scopes)");
		if (scopes == null) {
			setScopes(Collections.<String>emptyList());
		} else {
			setScopes(Arrays.asList(scopes));
		}
	}
	
	public void setScopes(List<String> scopes) {
		log.debug("\n\tsetScopes(List<String> scopes)");
		this.scopes.clear();
		this.supportedScopes.clear();
		for (String s: scopes) {
			this.scopes.add(s.toLowerCase());
			this.supportedScopes.add(SCOPE.valueOfLabel(s));
		}
	}
	public Set<SCOPE> getSupportedScopes() {
		return supportedScopes;
	}
	public boolean isScopeSupported(String scope) {
		return isScopeSupported(SCOPE.valueOfLabel(scope));
	}
	public boolean isScopeSupported(SCOPE scope) {
		return supportedScopes.contains(scope);
	}
	public void setDefault(boolean isDefault) {
		this.isDefault = isDefault;
	}
	
	public void setConfig(Map<String, Object> config) {
		this.config = config;
	}

	public JsonObject getOrigin() {
		return origin;
	}

	public void setOrigin(JsonObject origin) {
		this.origin = origin;
	}

	public void setCommonFields(Map<String, FieldElement> commonFields) {
		this.commonFields = commonFields;
		this.isEffectiveCalculated = false;
	}
	
}
