/*-
 * ~~~~~~licensing~~~~~~
 * core-support-runtime-legacy
 * ==========
 * 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.esb.system.common.aggregation;

import java.util.ArrayList;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.ExtendedExchange;
import org.apache.camel.processor.aggregate.jdbc.ClassLoadingAwareObjectInputStream;
import org.apache.camel.support.DefaultExchange;
import org.apache.camel.support.DefaultExchangeHolder;
import org.apache.camel.util.IOHelper;

/**
 * Adapted from HawtDBCamelCodec
 */
public class JdbcCamelCodec {

    public byte[] marshallExchange(CamelContext camelContext, Exchange exchange, boolean allowSerializedHeaders) throws IOException {
        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
        marshallExchange(camelContext, exchange, allowSerializedHeaders, bytesOut);
        return bytesOut.toByteArray();
    }

    public void marshallExchange(CamelContext camelContext, Exchange exchange, boolean allowSerializedHeaders, OutputStream outputStream) throws IOException {
        // use DefaultExchangeHolder to marshal to a serialized object
        DefaultExchangeHolder pe = DefaultExchangeHolder.marshal(exchange, false, allowSerializedHeaders);
        // add the aggregated size and timeout property as the only properties we want to retain
        DefaultExchangeHolder.addProperty(pe, Exchange.AGGREGATED_SIZE, exchange.getProperty(Exchange.AGGREGATED_SIZE, Integer.class));
        DefaultExchangeHolder.addProperty(pe, Exchange.AGGREGATED_TIMEOUT, exchange.getProperty(Exchange.AGGREGATED_TIMEOUT, Long.class));
        // add the aggregated completed by property to retain
        DefaultExchangeHolder.addProperty(pe, Exchange.AGGREGATED_COMPLETED_BY, exchange.getProperty(Exchange.AGGREGATED_COMPLETED_BY, String.class));
        // add the aggregated correlation key property to retain
        DefaultExchangeHolder.addProperty(pe, Exchange.AGGREGATED_CORRELATION_KEY, exchange.getProperty(Exchange.AGGREGATED_CORRELATION_KEY, String.class));
        DefaultExchangeHolder.addProperty(pe, Exchange.AGGREGATED_CORRELATION_KEY, exchange.getProperty(Exchange.AGGREGATED_CORRELATION_KEY, String.class));
        // and a guard property if using the flexible toolbox aggregator
        DefaultExchangeHolder.addProperty(pe, Exchange.AGGREGATED_COLLECTION_GUARD, exchange.getProperty(Exchange.AGGREGATED_COLLECTION_GUARD, String.class));
        // @ENTAXY-FIX GROUPED_EXCHANGE isn't marshaling
        if (exchange.getProperty(Exchange.GROUPED_EXCHANGE) != null && exchange.getProperty(Exchange.GROUPED_EXCHANGE) instanceof ArrayList) {
            DefaultExchangeHolder.addProperty(pe, Exchange.GROUPED_EXCHANGE, exchange.getProperty(Exchange.GROUPED_EXCHANGE, ArrayList.class));
        } else if (exchange.getProperty(Exchange.GROUPED_EXCHANGE) != null && exchange.getProperty(Exchange.GROUPED_EXCHANGE) instanceof StringBuffer) {
            DefaultExchangeHolder.addProperty(pe, Exchange.GROUPED_EXCHANGE, exchange.getProperty(Exchange.GROUPED_EXCHANGE, StringBuffer.class));
        }
        // persist the from endpoint as well
        if (exchange.getFromEndpoint() != null) {
            DefaultExchangeHolder.addProperty(pe, "CamelAggregatedFromEndpoint", exchange.getFromEndpoint().getEndpointUri());
        }
        encode(pe, outputStream);
    }

    public Exchange unmarshallExchange(CamelContext camelContext, byte[] buffer) throws IOException, ClassNotFoundException {
        return unmarshallExchange(camelContext, new ByteArrayInputStream(buffer));
    }

    public Exchange unmarshallExchange(CamelContext camelContext, InputStream inputStream) throws IOException, ClassNotFoundException {
        DefaultExchangeHolder pe = decode(camelContext, inputStream);
        Exchange answer = new DefaultExchange(camelContext);
        DefaultExchangeHolder.unmarshal(answer, pe);
        // restore the from endpoint
        String fromEndpointUri = (String) answer.removeProperty("CamelAggregatedFromEndpoint");
        if (fromEndpointUri != null) {
            Endpoint fromEndpoint = camelContext.hasEndpoint(fromEndpointUri);
            if (fromEndpoint != null) {
                answer.adapt(ExtendedExchange.class).setFromEndpoint(fromEndpoint);
            }
        }
        return answer;
    }

    private void encode(Object object, OutputStream bytesOut) throws IOException {
        try (ObjectOutputStream objectOut = new ObjectOutputStream(bytesOut)) {
            objectOut.writeObject(object);
        }
    }

    private DefaultExchangeHolder decode(CamelContext camelContext, InputStream bytesIn) throws IOException, ClassNotFoundException {
        ObjectInputStream objectIn = null;
        Object obj = null;
        try {
            objectIn = new ClassLoadingAwareObjectInputStream(camelContext, bytesIn);
            obj = objectIn.readObject();
        } finally {
            IOHelper.close(objectIn);
        }

        return (DefaultExchangeHolder)obj;
    }

}

