package de.dhbwstuttgart.typedeployment;

import org.antlr.v4.runtime.Token;

import de.dhbwstuttgart.typeinference.unify.model.ReferenceType;

import java.time.OffsetDateTime;
import java.util.List;
import java.util.stream.Collectors;

public class TypeInsertPoint {
    public Token point;
    private String insertString;
    private int extraOffset = 0;

    public TypeInsertPoint(Token point, String toInsert){
        this.point = point;
        this.insertString = (toInsert.endsWith(" ")) ? toInsert : toInsert + " " ;
    }

    public String insert(String intoSource, List<TypeInsertPoint> additionalOffset){
        int offset = additionalOffset.stream().filter((token ->
                //token.point.getLine() != point.getLine() && token.point.getCharPositionInLine() <= point.getCharPositionInLine()))
                token.point.getStartIndex() <= point.getStartIndex()))
                .mapToInt((typeInsertPoint -> typeInsertPoint.insertString.length())).sum();
        return new StringBuilder(intoSource).insert(point.getStartIndex()+offset+extraOffset, insertString).toString();
    }

    public String getInsertString() {
        return insertString;
    }
       
    public void addExtraOffset(int toAdd) {
    	this.extraOffset += toAdd;
    }
    
    public int getPositionInCode() {
    	return point.getStartIndex() + extraOffset; 
    }
    
    /* PL 2018-06-19
     * Zwei TypeInsertPoint's sind gleich, wenn ihre point's gleich sind 
     * eingefuegt damit man TypeReplaceMarker vergleichen kann
     * @see java.lang.Object#equals(java.lang.Object)
     */
    public boolean equals(Object obj) {
    	if(!(obj instanceof TypeInsertPoint)) {
			return false;
    	}
    	else {
    		return ((TypeInsertPoint)obj).point.equals(this.point) &&
    				((TypeInsertPoint)obj).insertString.equals(this.insertString);
    	}			
    }
    
    public String toString() {
    	return point.toString() + " " + insertString.toString();
    }
}
