/*-
 * ~~~~~~licensing~~~~~~
 * system-commons
 * ==========
 * Copyright (C) 2020 - 2021 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.esb.system.common.aggregation;

import org.apache.camel.AggregationStrategy;
import org.apache.camel.Exchange;

public class TimeoutAwareAggregationStrategyImpl implements AggregationStrategy {

    private static final String ACK_MESSAGE_HEADER = "NTX_AckMessage";

    private final String nameHeaderAcknowledge;

    public TimeoutAwareAggregationStrategyImpl(String nameHeaderAcknowledge) {
        this.nameHeaderAcknowledge = nameHeaderAcknowledge;
    }

    @Override
    public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
        if (oldExchange == null) {
            return newExchange;
        } else {
            oldExchange.getMessage().setHeader(nameHeaderAcknowledge, checkOnCorrectPair(oldExchange, newExchange));
            return oldExchange;
        }
    }

    private boolean checkOnCorrectPair(Exchange oldExchange, Exchange newExchange) {
        return (oldExchange != null && oldExchange.getMessage().getHeader(ACK_MESSAGE_HEADER) == null &&
                (newExchange == null || newExchange.getMessage().getHeader(ACK_MESSAGE_HEADER) == null));
    }

    @Override
    public void timeout(Exchange oldExchange, int index, int total, long timeout) {
        oldExchange.getMessage().setHeader(nameHeaderAcknowledge,
                (oldExchange.getMessage().getHeader(ACK_MESSAGE_HEADER) == null));
    }
}
