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

import java.io.InputStream;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.io.IOUtils;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;

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

import ru.entaxy.esb.platform.runtime.base.connecting.generator.Generated;
import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceMetadata;
import ru.entaxy.esb.resources.EntaxyResourceService;
import ru.entaxy.platform.base.support.JSONUtils;
import ru.entaxy.platform.core.producer.executor.builder.BuiltObject;
import ru.entaxy.platform.core.producer.executor.builder.DefaultBuiltObject;
import ru.entaxy.platform.core.producer.executor.builder.ObjectBuilder;
import ru.entaxy.platform.core.producer.executor.deployer.DeployedObject;
import ru.entaxy.platform.core.producer.executor.deployer.ObjectDeployer;
import ru.entaxy.platform.core.producer.executor.support.LocalPrintOutput;

@Component(service = {ObjectBuilder.class, ObjectDeployer.class})
public class ResourceObjectSupport implements ObjectBuilder, ObjectDeployer {

    private static final String RESOURCE_SECTION = "resource";
    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    EntaxyResourceService entaxyResourceService;

    /*
     * ObjectBuilder
     */
    @Override
    public boolean isBuildable(Generated generated) {
        return generated.getType().startsWith(ResourceDescriptor.RESOURCE_TYPE_PREFIX);
    }

    @Override
    public BuiltObject build(Generated generated, Map<String, Object> instructions) throws Exception {
        if (!isBuildable(generated))
            return null;

        LocalPrintOutput printer = new LocalPrintOutput(instructions);
        printer.printOutput(" = GENERATED PROPERTIES");
        for (Entry<String, Object> entry : generated.getProperties().entrySet()) {
            printer.printOutput(" :: " + entry.getKey() + " = [\n"
                    + (entry.getValue() == null ? "" : entry.getValue().toString())
                    + "\n]");
        }
        printer.printOutput(" = /GENERATED PROPERTIES");
        return new DefaultBuiltObject(new DeployableResource(generated.getProperties()));

    }

    /*
     * ObjectDeployer 
     */

    @Override
    public boolean isDeployable(BuiltObject object) {
        return object.getObject() instanceof DeployableResource;
    }

    @Override
    public DeployedObject deploy(BuiltObject object, Map<String, Object> instructions) throws Exception {
        if (!isDeployable(object))
            return null;
        LocalPrintOutput printer = new LocalPrintOutput(instructions);

        DeployableResource dr = (DeployableResource) object.getObject();
        printer.printOutput(" = RESOURCE TO DEPLOY");
        printer.printOutput(dr.getResourceUrl() + " [" + dr.resourceType + "/" + dr.endType + "]");

        EntaxyResource resource = entaxyResourceService.getResource(dr.getResourceUrl());
        resource.save(getInputStream(dr));

        String resourceType = dr.resourceType;
        JsonObject metadata = dr.getMetadataAsJson();
        if (!metadata.has(RESOURCE_SECTION))
            metadata.add(RESOURCE_SECTION, new JsonObject());
        JsonElement je = metadata.get(RESOURCE_SECTION);
        if (!je.isJsonObject()) {
            metadata.remove(RESOURCE_SECTION);
            je = new JsonObject();
            metadata.add(RESOURCE_SECTION, je);
        }
        JsonObject resourceSection = je.getAsJsonObject();
        if (!resourceSection.has("type"))
            resourceSection.addProperty("type", resourceType);

        EntaxyResourceMetadata resourceMetadata = resource.getMetadata(true);
        for (Entry<String, JsonElement> entry : metadata.entrySet()) {
            if (!entry.getValue().isJsonObject())
                continue;
            EntaxyResourceMetadata.MetadataSection section = resourceMetadata.getSection(entry.getKey());
            JSONUtils.mergeObjects(entry.getValue().getAsJsonObject(), section.getContent());
        }
        resourceMetadata.update();

        printer.printOutput(" :: DEPLOYED");

        // nothing to do with resource in further phases
        return null;
    }

    protected InputStream getInputStream(DeployableResource res) {
        if ((res == null) || (res.resourceContent == null))
            return getDefaultInputStream();
        if ("String".equals(res.endType))
            return IOUtils.toInputStream(res.resourceContent.toString());
        // TODO support other resource types
        return getDefaultInputStream();

    }

    protected InputStream getDefaultInputStream() {
        return IOUtils.toInputStream("");
    }
}
