package de.dhbwstuttgart.core;

import de.dhbwstuttgart.parser.JavaTXParser;
import de.dhbwstuttgart.syntaxtree.ClassOrInterface;
import de.dhbwstuttgart.syntaxtree.SourceFile;
import de.dhbwstuttgart.syntaxtree.SyntaxTreeNode;
import de.dhbwstuttgart.syntaxtree.factory.UnifyTypeFactory;
import de.dhbwstuttgart.typeinference.constraints.Constraint;
import de.dhbwstuttgart.typeinference.constraints.ConstraintSet;
import de.dhbwstuttgart.typeinference.unify.TypeUnify;
import de.dhbwstuttgart.typeinference.unify.interfaces.IFiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.FiniteClosure;
import de.dhbwstuttgart.typeinference.unify.model.UnifyPair;
import de.dhbwstuttgart.typeinference.unify.model.UnifyType;

import java.io.File;
import java.io.IOException;
import java.util.*;

public class JavaTXCompiler {

    private List<SourceFile> sourceFiles = new ArrayList<>();

    public void typeInference(){
        ConstraintSet cons = new ConstraintSet();
        List<ClassOrInterface> allClasses = new ArrayList<>();
        for(SourceFile sf : sourceFiles){
            allClasses.addAll(sf.getClasses());
        }
        FiniteClosure finiteClosure = UnifyTypeFactory.generateFC(allClasses);
        for(SourceFile sf : sourceFiles){
            cons.addAll(sf.getConstraints(sf.getTypeInferenceInformation(sourceFiles)));
        }
        ConstraintSet<UnifyPair> unifyCons = UnifyTypeFactory.convert(cons);

        TypeUnify unify = new TypeUnify();
        for(List<Constraint<UnifyPair>> xCons : unifyCons.cartesianProduct()){
            Set<UnifyPair> xConsSet = new HashSet<>();
            for(Constraint<UnifyPair> constraint : xCons){
                xConsSet.addAll(constraint);
            }

            System.out.println(xConsSet);
            Set<Set<UnifyPair>> result = unify.unify(xConsSet, finiteClosure);
            System.out.println(result);
        }

    }

    public void parse(File sourceFile) throws IOException, ClassNotFoundException {
        sourceFiles.add(new JavaTXParser().parse(sourceFile));
    }

}
