/*-
 * ~~~~~~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.executor.objectmodel;

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

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

import com.google.gson.JsonObject;

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


public abstract class AbstractFactored extends AbstractItem {

	private static final Logger log = LoggerFactory.getLogger(AbstractFactored.class);
	
	public static boolean isFactored(JsonObject jsonObject) {
		if (jsonObject.has(FIELDS.FACTORY_ID)) {
			String factoryId = jsonObject.get(FIELDS.FACTORY_ID).getAsString();
			return (factoryId != null) && !factoryId.isBlank(); 
		}
		return false;
	} 

	public static AbstractFactored getContextOwner(Map<String, Object> context) {
		initContext(context);
		@SuppressWarnings("unchecked")
		List<AbstractFactored> list = (List<AbstractFactored>)context.get(FACTORED_CONTEXT_KEY); 
		if (!list.isEmpty()) {
			return list.get(list.size()-1);
		}
		return null;
	}

	
	public String factoryId;
	public String scope = "public";
	public String ownScope = "";

	public List<AbstractItem> internalItems = new ArrayList<>();
	
	protected AbstractFactored(ObjectModel objectModel) {
		super(objectModel);
	}

	public void addInternal(AbstractItem item) {
		if (!this.internalItems.contains(item))
			this.internalItems.add(item);
	}
	
	public List<AbstractItem> getInternals(){
		return this.internalItems;
	}
	
	protected void joinContext(Map<String, Object> context) {
		initContext(context);
		@SuppressWarnings("unchecked")
		List<AbstractFactored> list = (List<AbstractFactored>)context.get(FACTORED_CONTEXT_KEY);
		list.add(this);
	}

	protected void leaveContext(Map<String, Object> context) {
		initContext(context);
		@SuppressWarnings("unchecked")
		List<AbstractFactored> list = (List<AbstractFactored>)context.get(FACTORED_CONTEXT_KEY);
		list.remove(this);
	}

	public void wrap(JsonObject object, Map<String, Object> context, String path) {
		super.wrap(object, context, path);
		this.factoryId = object.has(FIELDS.FACTORY_ID)?object.get(FIELDS.FACTORY_ID).getAsString():null;
		log.debug("WRAPPING FOR :: " + this.factoryId + "[" + jsonPath + "]");
	}
	
}
