package org.fda.inputdataparser;

import java.io.File;
import java.security.MessageDigest;
import java.util.List;
import org.fda.data.Utilities;
import org.fda.intervaltree.Interval;

/**
 *
 * @author Gokhan.Yavas
 */
public class FastaReader extends Reader{
    @Override
    
    public ReadRecord readNextRecord(){
        String line;
        String header=null;
        ReadRecord dr=null;
        StringBuilder sb= new StringBuilder();                
        boolean seqRead = false;
              
        
        try{
            MessageDigest digest = MessageDigest.getInstance(Utilities.hashalg.toString());
            MessageDigest digest2 = MessageDigest.getInstance(Utilities.hashalg.toString());
            while((line = br.readLine())!=null){
                line = line.trim();
                if(line.isEmpty()){
                    //skip the empty lines
                    continue;
                }
                
                if(line.startsWith(">")){                    
                    if(!seqRead){
                        header = line;
                        digest.update(header.getBytes("UTF-8"));
                    }
                    else {
                        br.reset();
                        break;
                    }
                }
                else{   
                    seqRead=true;
                    sb = sb.append(line);   
                    digest.update(line.getBytes("UTF-8"));
                    digest2.update(line.getBytes("UTF-8"));
                    br.mark(Utilities.mark4BackTrack);                    
                }
            }
            if(seqRead){
                //dr = new FastaRecord(header, sb.toString().replaceAll("[n]", "N"), digest.digest());
                dr = new FastaRecord(header, sb.toString(), digest.digest(), digest2.digest());
                readrecordnumber++;
            }
        }
        catch(Exception e){e.printStackTrace();}
        return dr;
    }
    
    public static void main(String[] args){
        File f = new File("contigs.fa");
        FastaReader r = new FastaReader();
        ReadRecord fr ;
        try{
            r.openFile(f);
            while((fr=r.readNextRecord())!=null){
                if(((FastaRecord)fr).getName().equalsIgnoreCase("contig508")){
                    List<Interval> ivt =((FastaRecord)fr).getnIntervalsTree().inOrder();
                    for(Interval i : ivt){
                        System.out.println(i.getlow()+"\t"+i.gethigh());
                    }
                    
                }
                System.out.println(((FastaRecord)fr).getName()+"\t"+((FastaRecord)fr).getNcount());
            }
            r.closeReader();
        }
        catch(Exception e){e.printStackTrace();}
    }
}
