/*-
 * ~~~~~~licensing~~~~~~
 * core-support-runtime
 * ==========
 * 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~~~~~~
 */
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
 * agreements. See the NOTICE file distributed with this work for additional information regarding
 * copyright ownership. The ASF licenses this file to You 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.
 */
package ru.entaxy.platform.core.support.runtime.camel.aggregation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import ru.entaxy.platform.base.support.CommonUtils;

/**
 * Aggregate result of pick expression into a single combined Exchange holding all the aggregated
 * bodies in a {@link String} as the message body.
 *
 * This aggregation strategy can used in combination with
 * {@link org.apache.camel.processor.Splitter} to batch messages
 * 
 * @since 3.0.0
 */
public class MapAggregationStrategy implements AggregationStrategy {

    protected enum VALUE_TYPE {
        EXCHANGE,
        MESSAGE,
        BODY
    }

    private static String DEFAULT_keySourceHeader = "AGGREGATION_MAP_KEY";

    private String keySourceHeader = DEFAULT_keySourceHeader;
    private String valueType = VALUE_TYPE.BODY.name();

    /**
     * Set keySourceHeader used for getting key
     * 
     * @param keySourceHeader The header to use as key source. Default AGGREGATION_MAP_KEY
     * @return
     */
    public MapAggregationStrategy keySourceHeader(String keySourceHeader) {
        this.keySourceHeader = keySourceHeader;
        return this;
    }

    /**
     * Set valueType used for getting value
     * 
     * @param valueType The string representing VALUE_TYPE enum element
     * @return
     */
    public MapAggregationStrategy valueType(String valueType) {
        try {
            this.valueType = VALUE_TYPE.valueOf(valueType).name();
        } catch (Exception e) {
            this.valueType = VALUE_TYPE.BODY.name();
        }
        return this;
    }

    @Override
    public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
        List<List<Object>> list;

        if (oldExchange == null) {
            list = getList(newExchange);
        } else {
            list = getList(oldExchange);
        }

        if (newExchange != null) {

            String key = getKey(newExchange);

            Object value = getValue(newExchange);

            if (CommonUtils.isValid(key)) {
                List<Object> lst = new ArrayList<>();
                lst.add(key);
                lst.add(value);
                list.add(lst);
            }
        }

        return oldExchange != null ? oldExchange : newExchange;
    }

    protected String getKey(Exchange exchange) {

        Object header = exchange.getIn().getHeader(keySourceHeader);
        if (header == null)
            header = exchange.getIn().getHeader(DEFAULT_keySourceHeader);
        if (header == null)
            return null;
        return header.toString();

    }

    protected Object getValue(Exchange exchange) {

        VALUE_TYPE vt = VALUE_TYPE.valueOf(valueType);

        switch (vt) {
            case EXCHANGE:
                return exchange;
            case MESSAGE:
                return exchange.getIn();
            default:
                return exchange.getIn().getBody();
        }

    }

    @SuppressWarnings("unchecked")
    private List<List<Object>> getList(Exchange exchange) {
        List<List<Object>> list = (List<List<Object>>) exchange.getProperty(Exchange.GROUPED_EXCHANGE, List.class);
        if (list == null) {
            list = new ArrayList<>();
            exchange.setProperty(Exchange.GROUPED_EXCHANGE, list);
        }
        return list;
    }


    @SuppressWarnings("unchecked")
    private Map<String, Object> getMap(Exchange exchange) {
        Map<String, Object> map = (Map<String, Object>) exchange.getProperty(Exchange.GROUPED_EXCHANGE, Map.class);
        if (map == null) {
            map = new HashMap<>();
            exchange.setProperty(Exchange.GROUPED_EXCHANGE, map);
        }
        return map;
    }

    @Override
    public void onCompletion(Exchange exchange) {

        if (exchange != null) {
            List<List<Object>> list = (List<List<Object>>) exchange.removeProperty(Exchange.GROUPED_EXCHANGE);
            if (list != null) {

                Map<String, Object> map = new HashMap<>();
                for (List<Object> l : list)
                    map.put(l.get(0).toString(), l.get(1));

                exchange.getIn().setBody(map);
            }
        }

    }

    public String getKeySourceHeader() {
        return keySourceHeader;
    }

    public void setKeySourceHeader(String keySourceHeader) {
        this.keySourceHeader = keySourceHeader;
    }

    public String getValueType() {
        return valueType;
    }

    public void setValueType(String valueType) {
        this.valueType = valueType;
    }

}
