package tree;

import java.util.LinkedList;
import java.util.List;

class ForestWithContours extends LinkedList<TreeWithContours>{
    LinkedList<Double> leftcontour;
    LinkedList<Double> rightcontour;
    double firstlast;

    ForestWithContours(List<? extends DrawableTreeNode> children){
	this.leftcontour=new LinkedList<Double>();
	this.rightcontour=new LinkedList<Double>();
	this.firstlast=0;
	for (DrawableTreeNode child:children){
	    add(new TreeWithContours(child));
	}
    }

    public boolean add(TreeWithContours newtree){
	if (super.isEmpty()){
	    leftcontour=newtree.leftcontour;
	    rightcontour=newtree.rightcontour;
	    }
	else{
	    double offset=1;
	    double x1=0;
	    double x2=firstlast;
	    double x3=firstlast+offset;
	    double x4=firstlast+offset;
	    LinkedList<Double> newleftcontour=new LinkedList<Double>();
	    LinkedList<Double> newrightcontour=new LinkedList<Double>();
	    while (!rightcontour.isEmpty()||!newtree.rightcontour.isEmpty())
		{
		    double a=x1;
		    double b=x4;
		    boolean leftempty=rightcontour.isEmpty();
		    boolean rightempty=newtree.rightcontour.isEmpty();
		    if (!leftempty){
			x1+=leftcontour.removeFirst();
			x2+=rightcontour.removeFirst();
		    }
		    if (!rightempty){
			x3+=newtree.leftcontour.removeFirst();
			x4+=newtree.rightcontour.removeFirst();
		    }
		    if (leftempty) x1=x3;
		    if (rightempty) x4=x2;
		    double decal=0;
		    if (!leftempty&&!rightempty&&x3<x2+1){
			decal = x2+1-x3; 
			offset+=decal;
			x3    +=decal;
			x4    +=decal;
		    }
		    newleftcontour.addLast(x1-a);
		    newrightcontour.addLast(x4-b-decal);
		}
	    newtree.setX(offset);
	    firstlast+=offset;
	    leftcontour=newleftcontour;
	    rightcontour=newrightcontour;
	}
	return super.add(newtree);
    }
}
