package org.fda.contiggenerator;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.fda.data.Enums.Orientation;
import org.fda.data.Utilities;
import org.fda.exceptions.IllegalIntervalException;
import org.fda.inputdataparser.FastaReader;
import org.fda.inputdataparser.FastaRecord;
import org.fda.inputdataparser.FastaWriter;
import org.fda.intervaltree.Interval;

/**
 *
 * @author Gokhan.Yavas
 */
public class ContigGenerator1 extends ContigGenerator implements ContigGeneratorInterface{
    //private BufferedReader br=null;
    private Map<String, List<ContigDetails>> intervalsMap= new HashMap<>();
    


    private ContigDetails parseInterval(String line) throws IllegalIntervalException{
        String[] top = line.split("\t");
        
        String name = top[0];
        Orientation or = Orientation.valueOf(top[2]);
                
        String[] ar1 = top[1].split(":");
        String refname = ar1[0];
        String[] coords = ar1[1].split("-");
        int st = Integer.parseInt(coords[0]);
        int end = Integer.parseInt(coords[1]);
        
        return new ContigDetails(name, refname, new Interval(st, end, false),  or, 0, 0);
    }    
    private void init(File f){
        ContigDetails tmp;
        List<ContigDetails> tmpList;
        try(BufferedReader br= new BufferedReader(new FileReader(f))){            
            //br = new BufferedReader(new FileReader(f));
            String line;
            line=br.readLine(); // skip the first line, which is header
            while((line=br.readLine())!=null){
                line = line.trim();
                if(line.isEmpty())
                    continue;
                tmp = parseInterval(line);
               
                if(intervalsMap.containsKey(tmp.getRefname()))
                    intervalsMap.get(tmp.getRefname()).add(tmp);
                else{
                    tmpList = new ArrayList<>();
                    tmpList.add(tmp);
                    intervalsMap.put(tmp.getRefname(), tmpList);                        
                }
                add2Lengths(tmp);                
            }
            
        } catch (IllegalIntervalException | IOException ex) {
            ex.printStackTrace();
        }
        this.totcontnumber = lengths.size();
        
    }
    public ContigGenerator1(File infile, File outfile, File f){
        super(infile, outfile);
        init(f);
    }    
    public ContigGenerator1(File infile, File outfile, File f, boolean createreport){
        super(infile, outfile, createreport);
        init(f);
    }    
    
    @Override
    public void generateContigs(){
    
        FastaReader fr = new FastaReader();
        FastaWriter frw = new FastaWriter(outfile);

                 
        Orientation or;
        try{
            fr.openFile(infile);
            FastaRecord r;
            while((r=((FastaRecord)fr.readNextRecord()))!=null){
//                if(r.getReadRecordLength()<Utilities.simulation_mincontiglength){
//                    System.out.println("This reference chromosome is smaller than "+Utilities.simulation_mincontiglength+" base pairs, which is the minimum required length");
//                    System.out.println("Hence no contigs would be created using this reference chromosome");
//                    continue;
//                }
             
                FastaRecord frec;
                totrefsize+=r.getReadRecordLength();
                totrefnumber++;
                // calculate the total gaps in reference r
                totalNReference+=r.getNcount();

                Interval it;

                List<ContigDetails> intervalsList = intervalsMap.get(r.getName());
                ContigDetails cd;
                if(intervalsList !=null){
                    for(int i=0; i<intervalsList.size(); i++){
                        cd = intervalsList.get(i);
                        it = intervalsList.get(i).getIr();
                        or =  intervalsList.get(i).getOr();
                        String s=r.getRead().substring(it.getlow()-1, it.gethigh());
                        if(or == Orientation.R)
                            s = Utilities.reverseComplement(s);

                        frec = new FastaRecord(">"+intervalsList.get(i).getName(), s);                                                
                        finalcontigcoords.add(new ContigDetails(cd.getName(), cd.getRefname(), cd.getIr(), cd.getOr(), frec.getNcount(), frec.getNratio()));
                        totsize+=frec.getReadRecordLength();
                        totalN+=frec.getNcount();
                        frw.write(frec);
                    }                    
                }
            }
            fr.closeReader();
            report();
        }
        catch(IOException io){io.printStackTrace();}
        finally{
            frw.closeWriter();
        }
    }
    
}
