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

import java.util.Collections;
import java.util.Map;

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

import ru.entaxy.esb.platform.runtime.base.connecting.generator.Generated;
import ru.entaxy.esb.platform.runtime.base.extensions.api.EntaxyExtensionsProvider;
import ru.entaxy.platform.base.objects.EntaxyObject;
import ru.entaxy.platform.base.objects.factory.EntaxyFactoryException;
import ru.entaxy.platform.core.producer.api.EntaxyProducerService;
import ru.entaxy.platform.core.producer.api.ProducerResult;
import ru.entaxy.platform.core.producer.api.ProducerResult.CommandResult;
import ru.entaxy.platform.core.producer.executor.generationmodel.merge.MergeHelper;
import ru.entaxy.platform.core.producer.executor.support.EntaxyObjectPropertiesHelper;

public class MergeTask extends AbstractTask {

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

    protected AbstractTask fromTask;
    protected AbstractTask toTask;

    public MergeTask(AbstractTask fromTask, AbstractTask toTask) {
        this.fromTask = fromTask;
        this.toTask = toTask;
        this.fromTask.mergeTo(this.toTask);
    }

    @Override
    public String getInfo() {
        return "MERGE: " + "\n\t FROM: " + fromTask.getInfo() + "\n\t TO: " + toTask.getInfo();
    }

    @Override
    public boolean execute(ProducerResult currentResult, CommandResult currentCommand,
            EntaxyProducerService producerService, Map<String, Object> instructions) throws Exception {

        Generated source = this.fromTask.getGeneratedResult();
        Generated target = this.toTask.getGeneratedResult();

        if ((source != null) && (target != null)) {

            if (!MergeHelper.getInstance().canMerge(source.getType(), target.getType())) {
                printOutput("CAN'T MERGE " + source.getType() + " TO " + target.getType());
                log.error("CAN'T MERGE " + source.getType() + " TO " + target.getType());
                throw new EntaxyFactoryException(
                        "Can not merge [" + source.getType() + "] to [" + target.getType() + "]");
            }

            EntaxyExtensionsProvider extensionsProvider =
                    currentResult.findResultObject(EntaxyExtensionsProvider.class);
            if (extensionsProvider == null)
                this.generatedResult = MergeHelper.getInstance().merge(source, target, Collections.emptyList());
            else
                this.generatedResult =
                        MergeHelper.getInstance().merge(source, target, extensionsProvider.getExtensions());

            // merge headers

            // GeneratedHeaders sourceGeneratedHeaders =
            // GeneratedHeaders.getHeaders(source.getProperties());
            // GeneratedHeaders targetGeneratedHeaders =
            // GeneratedHeaders.getHeaders(target.getProperties());

            GeneratedHeaders sourceGeneratedHeaders = GeneratedHeaders.getHeaders(
                    EntaxyObjectPropertiesHelper.getMainObjectProperties(source.getProperties()));
            GeneratedHeaders targetGeneratedHeaders = GeneratedHeaders.getHeaders(
                    EntaxyObjectPropertiesHelper.getMainObjectProperties(target.getProperties()));


            GeneratedHeaders resultGeneratedHeaders = GeneratedHeaders.getHeaders(
                    // this.generatedResult.getProperties()
                    EntaxyObjectPropertiesHelper.getMainObjectProperties(this.generatedResult.getProperties()));

            for (String header : targetGeneratedHeaders.headers.keySet())
                resultGeneratedHeaders.set(header, targetGeneratedHeaders.headers.get(header));

            for (String header : sourceGeneratedHeaders.headers.keySet())
                if (EntaxyObject.HEADERS.MAIN_OBJECT.equals(header)
                        || EntaxyObject.HEADERS.ENTAXY_GENERATED.equals(header))
                    continue;
                else
                    resultGeneratedHeaders.append(header, sourceGeneratedHeaders.headers.get(header));
        } else {
            if (source != null)
                this.generatedResult = source;
            else if (target != null)
                this.generatedResult = target;
            else
                // nothing to do
                return true;
        }

        this.fromTask.setFinal(false);
        this.toTask.updateGenerated(generatedResult);

        printOutput("\tMERGE RESULT ::");
        printOutput(generatedResult.getObject().toString());

        // prevent building result of this task
        this.generatedResult = null;

        return true;
    }



}
