/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.broad.igv.preprocess;

import java.io.File;
import java.io.IOException;
import net.sf.samtools.SAMFileReader;
import net.sf.samtools.SAMRecord;
import net.sf.samtools.util.CloseableIterator;

/**
 *
 * @author jrobinso
 */
public class SAMFileIterator implements AlignmentFileIterator {

    CloseableIterator<SAMRecord> iter;
    Alignment nextAlignment;

    public SAMFileIterator(File file) {

        SAMFileReader reader = new SAMFileReader(file);
        reader.setValidationStringency(SAMFileReader.ValidationStringency.SILENT);
        iter = reader.iterator();
        advance();

    }

    private void advance() {
        if(iter.hasNext()) {
            SAMRecord record = iter.next();
            nextAlignment = new Alignment(record.getReferenceName(),
                    record.getAlignmentStart(), record.getAlignmentEnd(),
                    record.getReadNegativeStrandFlag());
            nextAlignment.setMappingQuality(record.getMappingQuality());
            nextAlignment.setDuplicate(record.getDuplicateReadFlag());
        }
        else {
            nextAlignment = null;
        }
    }

    public boolean hasNext() {
        return nextAlignment != null;
    }

    public Alignment next() throws IOException {
        Alignment retValue = nextAlignment;
        advance();
        return retValue;
    }

    public void close() throws IOException {
        iter.close();
    }
    /*
    reader  = new SAMFileReader(samFile);
    CloseableIterator<SAMRecord> iter = reader.iterator();
    while

    (
    iter   .hasNext()


    ) {
    SAMRecord record = iter.next();

     */
}
