/*-
 * ~~~~~~licensing~~~~~~
 * object-producing-resources-support
 * ==========
 * 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.resources.impl;

import java.util.Map;

import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceService;
import ru.entaxy.platform.base.support.CommonUtils;
import ru.entaxy.platform.core.producer.api.EntaxyFactoryDataProcessor;
import ru.entaxy.platform.core.producer.resources.ResourceDataProcessor;
import ru.entaxy.platform.core.producer.resources.ResourceDescriptor;
import ru.entaxy.platform.core.producer.resources.StringFormatterService;

@Component(service = {EntaxyFactoryDataProcessor.class, ResourceDataProcessor.class}, immediate = true)
public class ResourceDataProcessorImpl implements EntaxyFactoryDataProcessor, ResourceDataProcessor {

    private static final Logger log = LoggerFactory.getLogger(ResourceDataProcessorImpl.class);

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    EntaxyResourceService entaxyResourceService;

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    StringFormatterService stringFormatterService;

    @Override
    public Object processDefaultValue(Object currentValue) {
        // log.info("\n-->> PROCESSING :: " +
        // (currentValue==null?"NULL":currentValue.getClass().getName()));
        if (currentValue == null)
            return currentValue;
        ResourceDescriptor descriptor = null;
        if (currentValue instanceof JsonElement) {
            // log.info("\n-->> PROCESSING :: JsonElement");
            if (((JsonElement) currentValue).isJsonObject()) {
                // log.info("\n-->> PROCESSING :: JsonObject");
                JsonObject jsonObject = ((JsonElement) currentValue).getAsJsonObject();
                if (jsonObject.has(ENTAXY_RESOURCE_KEY)) {
                    // log.info("\n-->> PROCESSING :: entaxy-resource");
                    descriptor = ResourceDescriptor.fromJson(jsonObject.get(ENTAXY_RESOURCE_KEY));
                }
            }
        } else if (currentValue instanceof Map) {
            // log.info("\n-->> PROCESSING :: MAP");
            if (((Map) currentValue).containsKey(ENTAXY_RESOURCE_KEY)) {
                Object current = ((Map) currentValue).get(ENTAXY_RESOURCE_KEY);
                // log.info("\n-->> PROCESSING :: SUBMAP :: " + current.getClass().getName());
                if (current instanceof Map) {
                    JsonElement je = (new Gson()).toJsonTree(current);
                    // log.info("\n-->> PROCESSING :: JE :: " + je.toString());
                    descriptor = ResourceDescriptor.fromJson(je);
                }
            }
        } else {
            // log.info("\n-->> PROCESSING :: NOT KNOWN");
        }
        if (descriptor != null) {
            Object result = getResourceDataFromDescriptor(descriptor);
            return result == null ? currentValue : result;
        }
        return currentValue;
    }

    @Override
    public Object getResourceDataFromDescriptor(ResourceDescriptor descriptor) {
        EntaxyResource resource = entaxyResourceService.getResource(descriptor.getResourceUrl());
        if (resource == null)
            return null;
        if (descriptor.isReturnResource())
            return resource;
        if (!resource.exists())
            return null;
        if ("String".equalsIgnoreCase(descriptor.endType)) {
            String resourceData = resource.getAsString();
            String format = descriptor.format;
            if (CommonUtils.isValid(format)) {
                log.debug("\n FORMAT :: " + format);
                resourceData = stringFormatterService.format(resourceData, format.split(","));
            }
            return resourceData;
        }
        return resource.getLocation();
    }

}
