package jgi;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;

import fileIO.ByteFile;
import fileIO.ByteFile1;
import fileIO.ByteFile2;
import fileIO.ByteStreamWriter;
import fileIO.FileFormat;
import fileIO.ReadWrite;
import shared.Parser;
import shared.Shared;
import shared.Timer;
import shared.Tools;
import stream.ConcurrentGenericReadInputStream;
import stream.FastaReadInputStream;
import stream.KillSwitch;
import structures.LongHashSet;

/**
 * From a 3-column text file of {node 1, node 2, dist},
 * makes a minimal representative set by retaining nodes
 * such that all original nodes are within a minumum distance
 * of at least one representative node.
 * Singleton nodes will only be included if they are 
 * represented by a self-edge.
 * 
 * @author Brian Bushnell
 * @date October 26, 2017
 *
 */
public class RepresentativeSet {
	
	public static void main(String[] args){
		Timer t=new Timer();
		RepresentativeSet sample=new RepresentativeSet(args);
		sample.process(t);
		sample.printResults(t);
	}
	
	public RepresentativeSet(String[] args){
		
		args=Parser.parseConfig(args);
		if(Parser.parseHelp(args, true)){
			printOptions();
			System.exit(0);
		}
		
		outstream.println("Executing "+getClass().getName()+" "+Arrays.toString(args)+"\n");
		
		ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
		ReadWrite.MAX_ZIP_THREADS=Shared.threads();
		
		Parser parser=new Parser();
		for(int i=0; i<args.length; i++){
			String arg=args[i];
			String[] split=arg.split("=");
			String a=split[0].toLowerCase();
			String b=split.length>1 ? split[1] : null;
			if(b==null || b.equalsIgnoreCase("null")){b=null;}
			while(a.startsWith("-")){a=a.substring(1);} //In case people use hyphens

			if(parser.parse(arg, a, b)){
				//do nothing
			}else if(a.equals("invalid")){
				outInvalid=b;
			}else if(a.equals("lines")){
				maxLines=Long.parseLong(b);
				if(maxLines<0){maxLines=Long.MAX_VALUE;}
			}else if(a.equals("thresh") || a.equals("threshold") || a.equals("minid")){
				threshold=Float.parseFloat(b);
			}else if(a.equals("verbose")){
				verbose=Tools.parseBoolean(b);
				ByteFile1.verbose=verbose;
				ByteFile2.verbose=verbose;
				stream.FastaReadInputStream.verbose=verbose;
				ConcurrentGenericReadInputStream.verbose=verbose;
				stream.FastqReadInputStream.verbose=verbose;
				ReadWrite.verbose=verbose;
			}else{
				outstream.println("Unknown parameter "+args[i]);
				assert(false) : "Unknown parameter "+args[i];
				//				throw new RuntimeException("Unknown parameter "+args[i]);
			}
		}
		
		{//Process parser fields
			overwrite=parser.overwrite;
			append=parser.append;
			
			in1=parser.in1;

			out1=parser.out1;
		}
		
		assert(FastaReadInputStream.settingsOK());
		
		if(in1==null){
			printOptions();
			throw new RuntimeException("Error - at least one input file is required.");
		}
		
		if(!ByteFile.FORCE_MODE_BF2){
			ByteFile.FORCE_MODE_BF2=false;
			ByteFile.FORCE_MODE_BF1=true;
		}

		if(out1!=null && out1.equalsIgnoreCase("null")){out1=null;}
		
		if(!Tools.testOutputFiles(overwrite, append, false, out1)){
			outstream.println((out1==null)+", "+out1);
			throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+"\n");
		}

		ffout1=FileFormat.testOutput(out1, FileFormat.TXT, null, true, overwrite, append, false);
		ffoutInvalid=FileFormat.testOutput(outInvalid, FileFormat.TXT, null, true, overwrite, append, false);
		ffin1=FileFormat.testInput(in1, FileFormat.TXT, null, true, true);
	}
	
	void process(Timer t){
		
		HashMap<Long, Node> map=load();
		LongHashSet set=new LongHashSet();
		
		ArrayList<Node> list=new ArrayList<Node>(map.size());
		list.addAll(map.values());
		Collections.sort(list);
		Collections.reverse(list);
		assert(list.size()==0 || list.get(0).sum>=list.get(list.size()-1).sum);
		
		for(Node n : list){
			assert(!n.used);
			boolean ok=true;
			if(n.edges!=null){
				for(Edge e : n.edges){
					if(set.contains(e.b)){
						ok=false;
						break;
					}
				}
			}
			if(ok){
				set.add(n.id);
				n.used=true;
			}
		}

		ByteStreamWriter bsw=null;
		if(ffout1!=null){
			bsw=new ByteStreamWriter(ffout1);
			bsw.start();
		}
		
		ByteStreamWriter bswInvalid=null;
		if(ffoutInvalid!=null){
			bswInvalid=new ByteStreamWriter(ffoutInvalid);
			bswInvalid.start();
		}
		
		for(Node n : list){
			if(n.used){
				nodesValid++;
				if(bsw!=null){
					bsw.println(n.id);
				}
			}else{
				if(bswInvalid!=null){
					bswInvalid.println(n.id);
				}
			}
		}
		
		if(bsw!=null){errorState|=bsw.poisonAndWait();}
		if(bswInvalid!=null){errorState|=bswInvalid.poisonAndWait();}
	}
	
	private HashMap<Long, Node> load(){
		ByteFile bf=ByteFile.makeByteFile(ffin1);
		
		HashMap<Long, Node> map=new HashMap<Long, Node>();
		
		byte[] line=bf.nextLine();
		if(line!=null && (Tools.startsWith(line, "Query\t") || line[0]=='#')){
			line=bf.nextLine();
		}
		
		while(line!=null){
			if(line.length>0){
				if(maxLines>0 && linesProcessed>=maxLines){break;}
				linesProcessed++;
				bytesProcessed+=line.length;
				Edge e=new Edge(line);
				if(e.dist>=threshold){
					Node n=map.get(e.a);
					if(n==null){
						nodesProcessed++;
						n=new Node(e.a);
						map.put(e.a, n);
					}
					if(e.a!=e.b){n.add(e);}
				}
			}
			line=bf.nextLine();
		}
		
		errorState|=bf.close();
		return map;
	}
	
	private void printResults(Timer t){
		t.stop();

		double rpnano=linesProcessed/(double)(t.elapsed);
		double npnano=nodesProcessed/(double)(t.elapsed);
		double bpnano=bytesProcessed/(double)(t.elapsed);

		String rpstring=(linesProcessed<100000 ? ""+linesProcessed : linesProcessed<100000000 ? (linesProcessed/1000)+"k" : (linesProcessed/1000000)+"m");
		String npstring=(nodesProcessed<100000 ? ""+nodesProcessed : nodesProcessed<100000000 ? (nodesProcessed/1000)+"k" : (nodesProcessed/1000000)+"m");
		String bpstring=(bytesProcessed<100000 ? ""+bytesProcessed : bytesProcessed<100000000 ? (bytesProcessed/1000)+"k" : (bytesProcessed/1000000)+"m");

		while(rpstring.length()<8){rpstring=" "+rpstring;}
		while(npstring.length()<8){npstring=" "+npstring;}
		while(bpstring.length()<8){bpstring=" "+bpstring;}
		
		outstream.println("Time:                         \t"+t);
		outstream.println("Lines Processed:    "+rpstring+" \t"+String.format(Locale.ROOT, "%.2fk lines/sec", rpnano*1000000));
		outstream.println("Nodes Processed:    "+npstring+" \t"+String.format(Locale.ROOT, "%.2fk lines/sec", npnano*1000000));
		outstream.println("Bytes Processed:    "+bpstring+" \t"+String.format(Locale.ROOT, "%.2fm bytes/sec", bpnano*1000));
		
		outstream.println();
		outstream.println("Valid Nodes:       \t"+nodesValid);
		outstream.println("Invalid Nodes:     \t"+(nodesProcessed-nodesValid));
		
		if(errorState){
			throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
		}
	}
	
	/*--------------------------------------------------------------*/
	
	/** This is called if the program runs with no parameters */
	private void printOptions(){assert(false) : "Please read the associated shell script for usage information.";}
	
	/*--------------------------------------------------------------*/
	
	
	private class Node implements Comparable<Node> {
		
		Node(long id_){
			id=id_;
		}
		
		void add(Edge e){
			if(edges==null){edges=new ArrayList<Edge>();}
			edges.add(e);
			sum+=e.dist-threshold;
		}
		
		@Override
		public int compareTo(Node b) {
			if(sum>b.sum){return 1;}
			if(sum==b.sum){return 0;}
			return -1;
		}
		
		final long id;
		ArrayList<Edge> edges;
		boolean used=false;
		double sum;
		
	}
	
	private class Edge {
		
		Edge(byte[] line){
			String[] split=new String(line).split("\t+");
			try {
				a=Long.parseLong(split[0]);
				b=Long.parseLong(split[1]);
				dist=Float.parseFloat(split[2]);
			} catch (NumberFormatException e) {
				System.err.println(new String(line)+"\n"+Arrays.toString(split));
				e.printStackTrace();
				KillSwitch.kill();
				throw new RuntimeException();
			}
		}
		
		Edge(long a_, long b_, double dist_){
			a=a_;
			b=b_;
			dist=dist_;
		}
		
		final long a;
		final long b;
		final double dist;
		
	}
	
	/*--------------------------------------------------------------*/
	
	private String in1=null;
	private String out1=null;
	private String outInvalid=null;
	
	/*--------------------------------------------------------------*/

	private long nodesProcessed=0;
	private long nodesValid=0;
	private long linesProcessed=0;
	private long bytesProcessed=0;
	
	private long maxLines=Long.MAX_VALUE;
	
	private double threshold=0;
	
	/*--------------------------------------------------------------*/
	
	private final FileFormat ffin1;
	private final FileFormat ffout1;
	private final FileFormat ffoutInvalid;
	
	
	/*--------------------------------------------------------------*/
	
	private PrintStream outstream=System.err;
	public static boolean verbose=false;
	public boolean errorState=false;
	private boolean overwrite=false;
	private boolean append=false;
	
}
