/*
 * Copyright (c) 2022 MiLaboratories Inc.
 *
 * 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.milaboratory.core.io.sequence;

import com.milaboratory.util.CanReportProgress;

import java.util.Arrays;
import java.util.List;

public final class ConcatenatingSingleReader implements SingleReader, CanReportProgress {
    private int currentPortIndex = 0;
    private long readIdOffset = 0;
    private final SingleReader[] singleReaders;

    public ConcatenatingSingleReader(List<SingleReader> singleReaders) {
        this(singleReaders.toArray(new SingleReader[0]));
    }

    public ConcatenatingSingleReader(SingleReader... singleReaders) {
        this.singleReaders = singleReaders;
    }

    @Override
    public synchronized long getNumberOfReads() {
        return Arrays.stream(singleReaders)
                .mapToLong(SequenceReader::getNumberOfReads)
                .sum();
    }

    @Override
    public synchronized SingleRead take() {
        while (currentPortIndex < singleReaders.length) {
            SingleRead read = singleReaders[currentPortIndex].take();
            if (read != null)
                return read.setReadId(read.getId() + readIdOffset);
            readIdOffset += singleReaders[currentPortIndex].getNumberOfReads();
            currentPortIndex++;
        }
        return null;
    }

    @Override
    public synchronized void close() {
        for (SingleReader r : singleReaders)
            r.close();
    }

    @Override
    public double getProgress() {
        return Arrays.stream(singleReaders)
                .mapToDouble(r -> r instanceof CanReportProgress
                        ? ((CanReportProgress) r).getProgress()
                        : Double.NaN)
                .sum() / singleReaders.length;
    }

    @Override
    public boolean isFinished() {
        return currentPortIndex == singleReaders.length;
    }
}
