package com.atlassian.stash.internal.concurrent;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Implementation of {@link TransferableState} that is a container of {@link TransferableState} instances. When 
 * {@link #apply()} is called, {@link TransferableState#apply()} is called on all contained states. Similarly, 
 * when {@link #remove()} is called, {@link TransferableState#remove()} is called on all contained states.
 *
 * @since 1.3
 */
public class CompositeTransferableState implements TransferableState {
    private static final Logger log = LoggerFactory.getLogger(CompositeTransferableState.class);

    private final List<TransferableState> states;

    public CompositeTransferableState(Iterable<TransferableState> states) {
        this.states = ImmutableList.copyOf(states);
    }

    @Override
    public void apply() {
        for (TransferableState state : states) {
            try {
                state.apply();
            } catch (Exception e) {
                log.warn("Failed to apply thread state", e);
            }
        }
    }

    @Override
    public void remove() {
        for (TransferableState state : states) {
            try {
                state.remove();
            } catch (Exception e) {
                log.warn("Failed to remove thread state", e);
            }
        }
    }

    @VisibleForTesting
    List<TransferableState> getStates() {
        return states;
    }
}
