/*
 * Copyright 2025 Todd Ginsberg
 *
 * 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.
 */

package com.ginsberg.gatherers4j;

import org.jspecify.annotations.Nullable;

import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Gatherer;

import static com.ginsberg.gatherers4j.util.GathererUtils.mustNotBeNull;
import static com.ginsberg.gatherers4j.util.GathererUtils.pushAll;

public class UniquelyOccurringGatherer<INPUT extends @Nullable Object, MAPPED extends @Nullable Object>
        implements Gatherer<INPUT, UniquelyOccurringGatherer.State<INPUT, MAPPED>, INPUT> {

    private final Function<INPUT, MAPPED> mappingFunction;

    UniquelyOccurringGatherer(final Function<@Nullable INPUT, @Nullable MAPPED> mappingFunction) {
        this.mappingFunction = mustNotBeNull(mappingFunction, "Mapping function must not be null");
    }

    @Override
    public Supplier<State<INPUT, MAPPED>> initializer() {
        return State::new;
    }

    @Override
    public Integrator<State<INPUT, MAPPED>, INPUT, INPUT> integrator() {
        return Integrator.ofGreedy((state, element, downstream) -> {
            final MAPPED mappedObject = mappingFunction.apply(element);
            if (!state.duplicates.contains(mappedObject)) {
                if (state.found.containsKey(mappedObject)) {
                    state.duplicates.add(mappedObject);
                    state.found.remove(mappedObject);
                } else {
                    state.found.put(mappedObject, element);
                }
            }
            return !downstream.isRejecting();
        });
    }

    @Override
    public BinaryOperator<State<INPUT, MAPPED>> combiner() {
        return (left, right) -> {
            for (final MAPPED element : right.duplicates) {
                left.duplicates.add(element);
                left.found.remove(element);
            }

            for (final Map.Entry<MAPPED, INPUT> element : right.found.entrySet()) {
                if (!left.duplicates.contains(element.getKey())) {
                    if (left.found.containsKey(element.getKey())) {
                        left.found.remove(element.getKey());
                        left.duplicates.add(element.getKey());
                    } else {
                        left.found.put(element.getKey(), element.getValue());
                    }
                }
            }
            return left;
        };
    }

    @Override
    public BiConsumer<State<INPUT, MAPPED>, Downstream<? super INPUT>> finisher() {
        return (inputState, downstream) -> pushAll(inputState.found.values(), downstream);
    }

    public static class State<INPUT, MAPPED> {
        final Set<@Nullable MAPPED> duplicates = new HashSet<>();
        final Map<@Nullable MAPPED, @Nullable INPUT> found = new LinkedHashMap<>();
    }
}
