/*-
 * ~~~~~~licensing~~~~~~
 * object-producer-core
 * ==========
 * 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.generationmodel;

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;
import ru.entaxy.platform.base.support.JSONUtils;

public class DefaultObjectDataResolver implements ObjectDataResolver {

	@Override
	public String getSupportedObjectType() {
		return "*";
	}

	@Override
	public Object resolve(EntaxyObject sourceObject, String propertyName) {
		JsonObject jsonObject = JSONUtils.getJsonRootObject(sourceObject.getConfiguration());
		if (jsonObject.has(propertyName))
			return JSONUtils.element2object(jsonObject.get(propertyName));
		return resolveNotRoot(sourceObject, propertyName, jsonObject);
	}
	
	protected Object resolveNotRoot(EntaxyObject sourceObject, String propertyName, JsonObject jsonRoot) {
		if (!jsonRoot.has(FIELDS.PROPERTIES))
			return null;
		JsonElement propertiesElement = jsonRoot.get(FIELDS.PROPERTIES);
		if (!propertiesElement.isJsonObject())
			return null;
		JsonObject properties = propertiesElement.getAsJsonObject();
		if (!properties.has(propertyName))
			return null;
		return JSONUtils.element2object(properties.get(propertyName));
	}

}
