/*
 * 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 java.util.List;

public final class SequenceReadUtil {
    private SequenceReadUtil() {}

    public static SequenceRead construct(SingleRead... reads) {
        if (reads.length == 0)
            throw new IllegalArgumentException();

        if (reads.length == 1)
            return reads[0];
        else if (reads.length == 2)
            return new PairedRead(reads);
        else
            return new MultiRead(reads);
    }

    public static SequenceRead construct(List<SingleRead> reads) {
        return construct(reads.toArray(new SingleRead[0]));
    }

    public static SequenceRead setReadId(long readId, SequenceRead read) {
        if (readId == read.getId())
            return read;

        if (read instanceof SingleReadLazy)
            return ((SingleReadLazy) read).setReadId(readId);

        if (read.numberOfReads() == 1) {
            SingleRead sRead = read.getRead(0);
            return new SingleReadImpl(readId, sRead.getData(), sRead.getDescription());
        }

        int nReads = read.numberOfReads();
        SingleRead[] sReads = new SingleRead[nReads];
        for (int i = 0; i < sReads.length; i++)
            sReads[i] = (SingleRead) setReadId(readId, read.getRead(i));

        if (nReads == 2)
            return new PairedRead(sReads);
        else
            return new MultiRead(sReads);
    }
}
